Send email everytime php generates a fatal error - 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

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

How to gracefully abort yeoman generator on error?

I'm writing a yeoman generator and want to check some prerequisites, for example a git being installed. I can easily check this using .exec, but how do i gracefully abort generator and report error to user? I searched docs, but it seems that i'm missing some obvious way to do it. Any hints?
Throwing exception will of course abort generator, but is it a best way? Maybe something more user friendly? Not all yeoman users are able to read js exceptions.
The current state of error handling in the popular generators is quite diverse:
in the most cases they just log the error and return from the action and let the subsequnt actions run and return 0 status code:
generator-karma's setupTravis method:
if (err) {
this.log.error('Could not open package.json for reading.', err);
done();
return;
}
or set a custom abort property on error and skip further actions with cheking on the abort property but still return 0 status code:
generator-jhipster's CloudFoundryGenerator:
CloudFoundryGenerator.prototype.checkInstallation = function checkInstallation() {
if(this.abort) return;
var done = this.async();
exec('cf --version', function (err) {
if (err) {
this.log.error('cloudfoundry\'s cf command line interface is not available. ' +
'You can install it via https://github.com/cloudfoundry/cli/releases');
this.abort = true;
}
done();
}.bind(this));
};
or manually end the process with process.exit:
generator-mobile's configuringmethod:
if (err) {
self.log.error(err);
process.exit(1);
}
However none of these methods provide a good way to signal to the environment that something went wrong except the last one but directly calling process.exit is a design smell.
Throwing an exception is also an option but this presents also the stackstrace to the user which is not always a good idea.
The best option would be use the Environment.error method, which has some nice advantages:
the Environment is exposed thorough the env property of the yeoman.generators.Base
an error event is emitted which is handled by the yo cli code
the execution will result in a non zero (error) status code which is override-able
by default yo will display only the message and no stacktrace
the stacktrace can be optionally displayed with providing the --debug built-in option when re-running the generator.
With using this technique your action method would look like this:
module.exports = generators.Base.extend({
method1: function () {
console.log('method 1 just ran');
this.env.error("something bad is happened");
console.log('this won't be executed');
},
method2: function () {
console.log('this won't be executed');
}
});

Stubbing stripe subscription error

I'm trying to test my payment process and I'm stuck with the problem of stubbing the subscription, this is the error message I get :
Double "Stripe::Customer" received unexpected message :[] with ("subscription")
This is the relevant part of the code for stubbing subscription :
#subscription = double('Stripe::Subscription')
#subscription.stub(:id) { 1234 }
#customer.stub(:subscription) { [#subscription] }
When I try the payment with the test card and it works, but I want to have an automated test in place in case something changes which could impact the payments
Edit :
per mcfinnigan suggestion I changed he last bit of code to :
#customer.stub(:[]).with(:subscription).and_return { [#subscription] }
And now I get this error :
Double "Stripe::Customer" received :[] with unexpected arguments
expected: (:subscription)
got: ("subscription")
Please stub a default value first if message might be received with other args as well.
You're not stubbing the right thing - your error indicates that something is attempting to call the method [] (i.e. array or hash dereferencing) on your double #customer.
Check your code and see whether you are sending a [] to a customer object anywhere.
Are you positive the last line should not be
#customer.stub(:[]).with(:subscription).and_return { [#subscription] }
instead?

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