如何用Laravel记录或显示致命的PHP错误



PHP Version 8.1.3

Laravel Version 9.6

PHP致命错误:Allowed memory size of 1073741824 bytes耗尽(尝试分配20480字节)

我知道我可以通过增加内存限制或完全删除它来避免这个错误。

此错误发生在客户端进行的非常大的API调用中。避免这种情况的正确方法是通过分页,这是广泛使用的方法。

然而,如果页面被遗漏,这个错误仍然会发生,那么所有用户收到的都是一个错误码为500的空白响应。

我想知道的是,如果有任何方法来处理这个错误,以返回自定义消息给用户或将其写入到我们的自定义SQL日志中,就像我们在handler.php渲染函数中处理所有其他错误一样。

我已经阅读了旧的4.2 Laravel文档:https://laravel.com/docs/4.2/errors

有一种方法可以捕获致命错误。但是我在后来的版本中没有找到任何内容。

有人能帮忙吗?

Laravel有可终止中间件,你可以使用它在HTTP响应之后做一些工作,例如记录请求和响应数据。链接到文档:https://laravel.com/docs/9.x/middleware terminable-middleware

你也可以使用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) {
//
}

最新更新