Skip to content

Commit

Permalink
增加异常抛出统一状态码
Browse files Browse the repository at this point in the history
  • Loading branch information
cyd622 committed Aug 9, 2019
1 parent cff8505 commit 5eb7a2e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
> - [x] jwt-auth用户认证与无感知自动刷新
> - [x] jwt-auth多角色认证不串号
> - [x] 单一设备登陆
> - [x] 异常捕获,http状态码统一
-----

## 安装
Expand Down Expand Up @@ -274,8 +274,13 @@ protected $routeMiddleware = [
```
2.路由器修改
```
Route::middleware('api.refresh')->group(function () {
// jwt认证路由以及无感刷新路由
Route::middleware('api.refresh:api')->group(function () {
// api看守器登陆授权
...
});
Route::middleware('api.refresh:admin')->group(function () {
// admin看守器登陆授权
...
});
```
Expand All @@ -292,7 +297,7 @@ class LoginController extends Controller
* 自动刷新用户认证
> * 捕获到了 token 过期所抛出的 TokenExpiredException异常
> * 刷新用户的 token `$token = $this->auth->refresh();`
> * 使用一次性登录以保证此次请求的成功
> * 使用一次性登录以保证此次请求的成功 注意需要设置config jwt宽限时间
> * `Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);`
> * 在响应头中返回新的 token `$this->setAuthenticationHeader($next($request), $token);`
Expand Down
5 changes: 5 additions & 0 deletions src/Response/ExceptionReport.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,11 @@ public function report()
$message = current($this->exception->validator->errors()->all());
}

// 设置了强制状态码
if (config('laravel_api.exception.force_http_code')) {
$httpCode = config('laravel_api.exception.force_http_code');
}

return $this->setHttpCode($httpCode)->setStatusCode($statusCode)->message($message);
}
}
3 changes: 3 additions & 0 deletions src/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
],
],
'exception' => [
// 是否强制http状态码。null,空,false,表示不是强制
'force_http_code' => 200,
// 在获取不到异常信息的状态码时设置状态码,设置force_http_code时,不生效
'default_http_code' => 500,
'do_report' => [
UnauthorizedHttpException::class => [
Expand Down

0 comments on commit 5eb7a2e

Please sign in to comment.