Jam*_*rge 6 php error-handling slim
我刚刚用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));
};
};
Run Code Online (Sandbox Code Playgroud)
但我不是一直抛出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;
}
Run Code Online (Sandbox Code Playgroud)
问题更多来自上面的函数,因为slim框架决定隐式处理所有异常,我没有try catch用来捕获任何错误的权限
没那么难,很简单。重写代码:
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));
};
}
Run Code Online (Sandbox Code Playgroud)
那么这段代码有什么作用呢?您基本上像以前一样传递 a $response,此代码的作用是从$response对象获取状态代码并将其传递给withStatus()方法。
| 归档时间: |
|
| 查看次数: |
6515 次 |
| 最近记录: |