【问题标题】:PHP: Slim Framework Exception HandlingPHP:Slim 框架异常处理
【发布时间】:2016-01-16 13:32:29
【问题描述】:

我刚刚创建了一个带有 slim 框架的 API 应用程序,最初,在我的代码中,我使用依赖容器来处理所有抛出的异常,代码如下。

//Add container to handle all exceptions/errors, fail safe and return json
$container['errorHandler'] = function ($container) {
    return function ($request, $response, $exception) use ($container) {
        //Format of exception to return
        $data = [
            'message' => $exception->getMessage()
        ];
        return $container->get('response')->withStatus(500)
            ->withHeader('Content-Type', 'application/json')
            ->write(json_encode($data));
    };
};

但我不想一直抛出 500 Server Error,而是想添加其他 HTTPS 响应代码。我想知道我是否可以就如何解决这个问题获得帮助。

public static function decodeToken($token)
{
    $token = trim($token);
    //Check to ensure token is not empty or invalid
    if ($token === '' || $token === null || empty($token)) {
        throw new JWTException('Invalid Token');
    }
    //Remove Bearer if present
    $token = trim(str_replace('Bearer ', '', $token));

    //Decode token
    $token = JWT::decode($token, getenv('SECRET_KEY'), array('HS256'));

    //Ensure JIT is present
    if ($token->jit == null || $token->jit == "") {
        throw new JWTException('Invalid Token');
    }

    //Ensure User Id is present
    if ($token->data->uid == null || $token->data->uid == "") {
        throw new JWTException("Invalid Token");
    }
    return $token;
}

问题更多来自于上述函数,因为 slim 框架决定隐式处理所有异常,我无法使用try catch 来捕获任何错误

【问题讨论】:

    标签: php error-handling slim


    【解决方案1】:

    没那么难,很简单。重写代码:

    container['errorHandler'] = function ($container) {
        return function ($request, $response, $exception) use ($container) {
            //Format of exception to return
            $data = [
                'message' => $exception->getMessage()
            ];
            return $container->get('response')->withStatus($response->getStatus())
                ->withHeader('Content-Type', 'application/json')
                ->write(json_encode($data));
        };
    }
    

    那么这段代码有什么作用呢?你基本上像以前一样传递了一个$response,这段代码的作用是它从$response对象中获取状态码并将其传递给withStatus()方法。

    Slim Documentation for referring to status.

    【讨论】:

    • 是的,这行得通,但问题是我使用这个容器来捕获来自不同方法的自定义抛出的异常,这些方法无法访问 $response 对象,所以我无法从这些函数中设置状态代码抛出异常和苗条的框架不允许我捕获这个异常。
    • @JamesOkpeGeorge 恕我直言,您应该创建一个 Response 类的新对象,然后传递它。
    • @JamesOkpeGeorge 另外,对于您的新问题,请创建一个新问题。
    • @JamesOkpeGeorge 如果可行,请勾选此项。 :)
    【解决方案2】:

    你可以使用Slim\Http\Response对象的withJson()方法

    class CustomExceptionHandler
    {
    
        public function __invoke(Request $request, Response $response, Exception $exception)
        {
            $errors['errors'] = $exception->getMessage();
            $errors['responseCode'] = 500;
    
            return $response
                ->withStatus(500)
                ->withJson($errors);
        }
    }
    

    如果你使用依赖注入,你可以这样做

    $container = $app->getContainer();
    
    //error handler
    $container['errorHandler'] = function (Container $c) {
      return new CustomExceptionHandler();
    };
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2013-03-07
      • 2012-06-10
      • 2014-07-11
      • 2011-10-13
      相关资源
      最近更新 更多