How to catch errors in elua (namely NodeMCU) - lua

Let's say I'm importing something with:
t = require("ds18b20")
t.setup(1)
temperatura = t.read()
How do I catch an error like "Failed import"?
Doing stuff like pcall(t.setup(1)) just returns a syntax error.

If the error is raised by require not finding ds18b20, then you can do
ok, t = pcall(require, "ds18b20")
if not ok then
-- handle error, t has error message
else
-- can use t
end

Related

Is it possible to change the output of Lua error messages?

I managed to change the output of error messages by modifying the dbg_printf method. However, that method doesn't handle the following error messages:
lua: ?:0: attempt to call global 'log' (a nil value)
Which method(s) handle these types of errors?
The error message is from the file ldebug.c in the function luaG_typeerror. But i guess you are using an older Lua Version because my message is a bit different:
attempt to call a nil value (global 'log')
You sould try to prevent the error if you can:
if type(log) == "function" then
log()
end
or as #lhf said use pcall:
if pcall(log) then
-- no errors while running 'log'
...
else
-- 'log' raised an error: take appropriate actions
...
end
It should be simpler than digging into the C api.
like #lhf says:
if pcal(risky) then
print("this works")
else
print("phooey!")
end
alternatively you can stop the program and get your error message like this:
if pcal(risky) then
print("this works")
else
error("your error message here")
end

How to return a function value from pcall() in lua

My code (psuedo)
function foo(cmd)
return load(cmd) --Note that this could cause an error, should 'cmd' be an invalid command
end
function moo()
return "moo"
end
function yoo(something)
something.do()
end
cmd = io.read() --Note that a syntax error will call an error in load. Therefore, I use pcall()
local result, error = pcall(cmd)
print(result)
This code looks okay, and works, but my problem is if I type in moo() then result will only show whether or not the command was executed without an error (If the command calls an error, error will have its value).
On another note, if I want to call yoo(), I won't get a return value from it, so I want pcall()'s true / false (or any alternate means other than pcall())
Is there an alternate way to call moo(), get a return value, and also be able to catch any errors?
NOTE: I couldn't find any try catch equivalent other then pcall / xpcall.
A bit outdated but still without proper answer...
What you are looking for is a combination of both load() and pcall()
Use load()to compile the entered string cmd into something that can be executed (function).
Use pcall() to execute the function returned by load()
Both functions can return error messages. Get syntax error description from load() and runtime error description from pcall()
function moo()
return "moo"
end
function yoo(something)
something.do_something()
end
cmd = io.read()
-- we got some command in the form of a string
-- to be able to execute it, we have to compile (load) it first
local cmd_fn, err = load("return "..cmd);
if not cmd_fn then
-- there was a syntax error
print("Syntax error: "..err);
else
-- we have now compiled cmd in the form of function cmd_fn(), so we can try to execute it
local ok, result_or_error = pcall(cmd_fn)
if ok then
-- the code was executed successfully, print the returned value
print("Result: "..tostring(result_or_error));
else
-- runtime error, print error description
print("Run error: "..result_or_error)
end
end

Use assert with pcall in Lua

Depending if it errors are raised or not, pcall(function) may return:
Success: true and the return value[s] of the function.
Failure: false and the error.
In my case I'm calling a function to return a table, so in case of no errors I will get my data from the second return value, and in case of error I will print manage the error.
How can I do it with assert?
At first I wrote this:
local ret, data = pcall(the_function)
assert(ret, "Error: "..data)
-- use data from here on.
The problem is that the assert message is evaluated even in case of success, so when the call succeeds Lua complains about concatenating a string with a table.
This problem is due to the fact that I want to use assert and cite the error, but avoiding using something like if not ret then assert(false, "...") end.
Try this:
local ret, data = assert(pcall(the_function))
If you don't need to alter the error message from pcall lhf's suggestion is best.
Otherwise a solution is:
local ret, data = pcall( the_function )
assert( ret, type( data ) == 'string' and "Error: " .. data )
or this one, which is a cleaner approach:
local ret, data = pcall( the_function )
if not ret then error( "Error: " .. data ) end
this latter avoids completely to evaluate the error message expression if pcall doesn't give an error.

Send email everytime php generates a fatal error

How would I write a PHP code that would send me an email everytime I get a
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 14373306 bytes) in on line <b>443</b><br />.
I'm running a script wherein a user has this URL and it will be process by my code, but the problem here is that sometimes it results to a Fatal error Allowed memory size exhausted. I want an email to be sent to me that tells me that there has this error at the same time what URL is causing that error.
So the logic is something like this.
if( error == "Fatal Error Allowed memory Size" ) {
mail("myemail#email.com", "Fatal Error - URL: http://google.com");
}
I hope the instruction is pretty clear. Your help would be greatly appreciated and rewarded!
Thanks! :-)
You can look at using register_shutdown_function(). It can be used to execute on E_ERROR(fatal error)
register_shutdown_function('shutdown');
function shutdown()
{
if(!is_null($e = error_get_last()))
{
mail("myemail#email.com", "Fatal Error - ". var_export($e, true));
}
}
I would however echo thoughts in the comments above that this is best handled using log monitoring.
Init following function inside your php file.
register_shutdown_function('mail_on_error'); //inside your php script
/** If any file having any kind of fatal error, sln team will be notified when cron will
become fail : following is the name of handler and its type
E_ERROR: 1 | E_WARNING: 2 | E_PARSE: 4 | E_NOTICE: 8
*/
function mail_on_error() {
global $objSettings;
$error = error_get_last();
//print_r($error);
if ($error['type'] == 1) {
// update file path into db
$objSettings->update_records($id=1,array('fatal_error' => json_encode($error)));
$exception_in_file_path = __FILE__;
fatal_error_structure($exception_in_file_path);
}// end if
}// end mail_on_error
fatal_error_structure should be defined on some global location. like function.inc.php. This will send an email to registered user.
function fatal_error_structure($exception_in_file_path){
$subject = "FATAL: Cron Daemon has failed";
sln_send_mail(nl2br("Please check $exception_in_file_path, This cron having FATAL error."),
$subject, 'email#address.com',$name_reciever='', 'text/plain');
}// end fatal_error_structure
vKj

Get line number of an error in JScript run in Windows Script Host

Say, I have the following code that I run as a .JS file using the Windows Script Host:
try
{
ProduceAnError();
}
catch(e)
{
//How to get an error line here?
}
Is there any way to know the error line where an error (exception) occurred?
Sorry for my other reply. It wasn't very helpful :P
I believe what you are looking for is the ReferenceError's stack property. You can access it with the argument that you pass to the catch:
try {
someUndefinedFunction("test");
} catch(e) {
console.log(e.stack)
}
example output:
ReferenceError: someUndefinedFunction is not defined
at message (http://example.com/example.html:4:3)
at <error: TypeError: Accessing selectionEnd on an input element that cannot have a selection.>
at HTMLInputElement.onclick (http://example.com/example.html:25:4)
There isn't really a way to get a stack or even catch the line number programmatically. One can only see the line number when throwing an error. At best you can get the error code and description or you can make your own errors.
Here's the documentation.
And an example
try {
produceAnError();
} catch(e) {
WScript.echo((e.number>>16 & 0x1FFF)); // Prints Facility Code
WScript.echo((e.number & 0xFFFF)); // Prints Error Code
WScript.echo(e.description); // Prints Description
throw e;
}

Resources