自定义错误处理,无需 try/except 在 php Slim 框架中



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

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

例如,无论异常在代码中的哪个位置抛出,我都希望我的自定义 BadCustomerDataException(( 触发 HTTP 400 响应,WaitingForResourceException(( 触发 423 响应,FaultyServerIsDeadAgainException(( 触发 500 响应。

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

在 Slim 4 中,您可以向 ErrorMiddleware 添加自定义错误处理程序。您还可以在错误中间件之前添加自己的中间件,以捕获和映射您自己的异常:

<?php
use PsrHttpMessageServerRequestInterface;
use PsrHttpServerRequestHandlerInterface;
use SlimExceptionHttpNotFoundException;
use SlimMiddlewareErrorMiddleware;
use SlimPsr7Response;
// ...
// 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);

最新更新