0

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?

2
  • 1
    There's always error handling for all version of laravel: laravel.com/docs/9.x/errors Commented Nov 15, 2022 at 16:41
  • Out-of-memory errors are a special case of tricky, as they'll immediately terminate the script. As a result, you can not guarantee that your logging or custom API message will ever run. Commented Nov 15, 2022 at 17:04

1 Answer 1

1

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) { // } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, it has achieved what I want it to, However just so I can understand it fully, why would you // Turn off all error reporting error_reporting(0); ini_set('display_errors', 0);
Disabling error reporting is necessary to hide sensitive information from attackers. "Allowed memory size" - is not the only one fatal error that can occur.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.