在 php Slim 框架中没有 try/except 的自定义错误处理

使用 php 和 Slim Framework,有没有一种方法可以设置错误处理程序,以便我的自定义异常可以自动触发所需的 HTTP 响应,而无需强制我捕获所有不同的异常类型?

我从我使用python Flask 的项目中知道这样的例子,但不知道 php 等价物。

例如,无论在代码中的何处引发异常,我都希望我的自定义 BadCustomerDataException() 触发 HTTP 400 响应,WaitingForResourceException() 触发 423 响应,FaultyServerIsDeadAgainException() 触发 500 响应。

目前我正在使用 Slim 版本 3,并计划更新到版本 4。


有只小跳蛙
浏览 103回答 1
1回答

江户川乱折腾

在 Slim 4 中,您可以将自定义错误处理程序添加到 ErrorMiddleware。您还可以在 ErrorMiddleware 之前添加自己的中间件以捕获和映射您自己的异常:例子<?phpuse Psr\Http\Message\ServerRequestInterface;use Psr\Http\Server\RequestHandlerInterface;use Slim\Exception\HttpNotFoundException;use Slim\Middleware\ErrorMiddleware;use Slim\Psr7\Response;// ...// HttpNotFound Middleware$app->add(function (    ServerRequestInterface $request,     RequestHandlerInterface $handler    ) {    try {        return $handler->handle($request);    } catch (HttpNotFoundException $httpException) {        $response = (new Response())->withStatus(404);        $response->getBody()->write('404 Not found');        return $response;    }});$app->add(ErrorMiddleware::class);
打开App,查看更多内容
随时随地看视频慕课网APP