Slim Framework 共享异常处理器
Slim Framework shared exception handler
对于我的 Slim 3 API 中的每条路线,我有如下内容:
$app->get('/login', function(Request $request, Response $response)
{
try
{
# SOME MAGIC HERE
# ...
}
catch(\My\ExpectedParamException $e)
{
$response->withStatus(400); # bad request
}
catch(\My\ExpectedResultException $e)
{
$response->withStatus(401); # unauthorized
}
catch(Exception $e)
{
$this->logger->write($e->getMessage());
throw $e;
}
});
我会只写一次这个模式,尽可能避免代码冗余。基本上我的路线定义应该限于#SOME MAGIC HERE。 Slim 是否提供了一种仅在代码的一部分中捕获错误的方法?
是的,您可以在一个地方处理所有情况。只需定义您自己的错误处理程序并将其传递给 DI 容器:
$container = new \Slim\Container();
$container['errorHandler'] = function ($container) {
return function ($request, $response, $exception) use ($container) {
if ($exception instanceof \My\ExpectedParamException) {
return $container['response']->withStatus(400); # bad request
} elseif ($exception instanceof \My\ExpectedResultException) {
return $container['response']->withStatus(400); # unauthorized
}
return $container['response']->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
$app = new \Slim\App($container);
对于我的 Slim 3 API 中的每条路线,我有如下内容:
$app->get('/login', function(Request $request, Response $response)
{
try
{
# SOME MAGIC HERE
# ...
}
catch(\My\ExpectedParamException $e)
{
$response->withStatus(400); # bad request
}
catch(\My\ExpectedResultException $e)
{
$response->withStatus(401); # unauthorized
}
catch(Exception $e)
{
$this->logger->write($e->getMessage());
throw $e;
}
});
我会只写一次这个模式,尽可能避免代码冗余。基本上我的路线定义应该限于#SOME MAGIC HERE。 Slim 是否提供了一种仅在代码的一部分中捕获错误的方法?
是的,您可以在一个地方处理所有情况。只需定义您自己的错误处理程序并将其传递给 DI 容器:
$container = new \Slim\Container();
$container['errorHandler'] = function ($container) {
return function ($request, $response, $exception) use ($container) {
if ($exception instanceof \My\ExpectedParamException) {
return $container['response']->withStatus(400); # bad request
} elseif ($exception instanceof \My\ExpectedResultException) {
return $container['response']->withStatus(400); # unauthorized
}
return $container['response']->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
$app = new \Slim\App($container);