Slim Framework共享异常处理程序

时间:2017-06-02 12:28:46

标签: php slim-3

对于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是否提供了一种仅在代码的一部分中捕获错误的方法?

1 个答案:

答案 0 :(得分:1)

是的,您可以在一个地方处理所有方案。只需定义自己的错误处理程序并将其传递给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);

查看corresponding part of the framework documentation