I have a gateway script that returns JSON back to the client. In the script I use set_error_handler to catch errors and still have a formatted return.
It is subject to 'Allowed memory size exhausted' errors, but rather than increase the memory limit with something like ini_set('memory_limit', '19T'), I just want to return that the user should try something else because it used to much memory.
Are there any good ways to catch fatal errors?
As this answer suggests, you can use
register_shutdown_function()
to register a callback that'll checkerror_get_last()
.You'll still have to manage the output generated from the offending code, whether by the
@
(shut up) operator, orini_set('display_errors', false)
When run, this outputs
Caught at shutdown
. Unfortunately, theErrorException
exception object isn't thrown because the fatal error triggers script termination, subsequently caught only in the shutdown function.You can check the
$error
array in the shutdown function for details on the cause, and respond accordingly. One suggestion could be reissuing the request back against your web application (at a different address, or with different parameters of course) and return the captured response.I recommend keeping
error_reporting()
high (a value of-1
) though, and using (as others have suggested) error handling for everything else withset_error_handler()
andErrorException
.