Php Slim 不使用自定义 errorHandler 处理错误
Php Slim not handle errors with the custom errorHandler
我的自定义错误处理程序不适用于 Slim 3 框架。我没有收到 500 错误,而是收到状态为 200 的响应,并且正文中包含 html 错误详细信息。
这是我最小的、可验证的完整示例:
$c = new \Slim\Container();
$c['errorHandler'] = function ($c) {
return function($request, $response, $exception) use ($c) {
return $c['response']->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
$app = new \Slim\App($c);
$app->any('/foo', function($request, $response, $args) {
$data = json_encode($request->nonExistingMethod()); // error!
return $response->withJson($data);
});
$app->run();
我需要如何重构此示例才能使其正常工作?我怀疑这与错误的致命性质有关。但是这种情况怎么处理呢?
参考:http://www.slimframework.com/docs/handlers/error.html
编辑 1
为了在 api 风格的 Web 应用程序中使用,我使用的最终解决方案与这个问题的响应有细微的变化:
function checkForError() {
$last = error_get_last();
if ($last) {
@header("HTTP/1.0 500 Internal Server Error");
echo json_encode($last); // optional, includes error details in json format
}
}
error_reporting(0);
register_shutdown_function('checkForError');
你无法捕捉到所有这样的错误
然而,有一种方法可以捕获除内存错误之外的所有错误(或仅捕获那些试图分配的内存超出错误处理程序所需的错误)
function checkForError() {
$last = error_get_last();
if ($last) {
@header("HTTP/1.0 500 Internal Server Error");
echo 'we failed... sry';
}
}
register_shutdown_function('checkForError');
更新了 500 个状态 header
我的自定义错误处理程序不适用于 Slim 3 框架。我没有收到 500 错误,而是收到状态为 200 的响应,并且正文中包含 html 错误详细信息。
这是我最小的、可验证的完整示例:
$c = new \Slim\Container();
$c['errorHandler'] = function ($c) {
return function($request, $response, $exception) use ($c) {
return $c['response']->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
$app = new \Slim\App($c);
$app->any('/foo', function($request, $response, $args) {
$data = json_encode($request->nonExistingMethod()); // error!
return $response->withJson($data);
});
$app->run();
我需要如何重构此示例才能使其正常工作?我怀疑这与错误的致命性质有关。但是这种情况怎么处理呢?
参考:http://www.slimframework.com/docs/handlers/error.html
编辑 1
为了在 api 风格的 Web 应用程序中使用,我使用的最终解决方案与这个问题的响应有细微的变化:
function checkForError() {
$last = error_get_last();
if ($last) {
@header("HTTP/1.0 500 Internal Server Error");
echo json_encode($last); // optional, includes error details in json format
}
}
error_reporting(0);
register_shutdown_function('checkForError');
你无法捕捉到所有这样的错误
然而,有一种方法可以捕获除内存错误之外的所有错误(或仅捕获那些试图分配的内存超出错误处理程序所需的错误)
function checkForError() {
$last = error_get_last();
if ($last) {
@header("HTTP/1.0 500 Internal Server Error");
echo 'we failed... sry';
}
}
register_shutdown_function('checkForError');
更新了 500 个状态 header