user1829002
user1829002

Reputation: 61

How to log or display a Fatal PHP Error with Laravel

PHP Version 8.1.3

Laravel Version 9.6

PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 20480 bytes)

I do understand I could avoid this error by increasing the memory limit or removing it completely.

This error occurred on a very large API call made by the client. The correct way to avoid this is through our paging, which is what is widely used.

However, this error can still occur if the page is left out, then all the user receives is a blank response with an error code 500.

What I would like to find out is if there is anyway to handle this error to give back a custom message to the user or to write it to our Custom SQL logs like we do with all other errors in our handler.php render function.

I have read the old 4.2 Laravel documentation :https://laravel.com/docs/4.2/errors

That there was a way to capture fatal errors. But I do not find anything in the later versions.

Would anyone be able to help?

Upvotes: 0

Views: 667

Answers (1)

W S
W S

Reputation: 362

Laravel has Terminable Middleware which you can use to do some work after the HTTP response, for example logging request and response data. Link to docs: https://laravel.com/docs/9.x/middleware#terminable-middleware

You can also use php native "register_shutdown_function": https://www.php.net/manual/en/function.register-shutdown-function.php

// Turn off all error reporting
error_reporting(0);
ini_set('display_errors', 0);

// Register shutdown function:
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.
    echo 'Script executed with success';        
}

register_shutdown_function('shutdown');

// Trigger memory error:
try {
    $data = str_repeat("-", PHP_INT_MAX);
    
} catch(Exception $exception) {
    //
}

Upvotes: 1

Related Questions