php Slim 框架中没有 try/except 的自定义错误处理
custom error handling without try/except in php Slim framework
使用 php 和 Slim Framework,有没有一种方法可以设置错误处理程序,以便我的自定义异常可以自动触发所需的 HTTP 响应,而无需强制我捕获所有不同的异常类型?
我从我的 python Flask 项目中知道这样的例子,但不知道 php 等价物。
例如,无论在代码中的哪个位置抛出异常,我都希望我的自定义 BadCustomerDataException() 触发 HTTP 400 响应,WaitingForResourceException() 触发 423 响应,FaultyServerIsDeadAgainException() 触发500 个响应。
目前我使用的是 Slim 版本 3,计划更新到版本 4。
在 Slim 4 中,您可以向 ErrorMiddleware 添加自定义 error handler。您还可以在 ErrorMiddleware 之前添加自己的中间件以捕获和映射您自己的异常:
例子
<?php
use 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);
使用 php 和 Slim Framework,有没有一种方法可以设置错误处理程序,以便我的自定义异常可以自动触发所需的 HTTP 响应,而无需强制我捕获所有不同的异常类型?
我从我的 python Flask 项目中知道这样的例子,但不知道 php 等价物。
例如,无论在代码中的哪个位置抛出异常,我都希望我的自定义 BadCustomerDataException() 触发 HTTP 400 响应,WaitingForResourceException() 触发 423 响应,FaultyServerIsDeadAgainException() 触发500 个响应。
目前我使用的是 Slim 版本 3,计划更新到版本 4。
在 Slim 4 中,您可以向 ErrorMiddleware 添加自定义 error handler。您还可以在 ErrorMiddleware 之前添加自己的中间件以捕获和映射您自己的异常:
例子
<?php
use 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);