PHP:Slim框架异常处理

6

我刚刚用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 服务器错误,我想添加其他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来捕获任何错误。

2个回答

4

并不难,很简单。重写代码:

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文档了解更多关于状态码的信息。

是的,那个方法可以用,但问题在于我使用这个容器来捕获不同方法抛出的自定义异常,这些方法无法访问 $response 对象,因此我无法从抛出异常的函数中设置状态码,而 slim 框架也不允许我捕获这些异常。 - George
@JamesOkpeGeorge 在我看来,你应该创建 Response 类的一个新对象,然后再进行传递。 - codez
@JamesOkpeGeorge,另外,针对您的新问题,请创建一个新的问题。 - codez
@JamesOkpeGeorge 如果这个有效,请打勾 :) - codez

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();
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接