Php Slim无法处理自定义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状态标题

上一篇:PHP:超薄框架异常处理


下一篇:mysql – 无法使用Google App Engine上的Slim框架连接到Google Cloud SQL