12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
- namespace App\Exceptions;
- use Closure;
- use Exception;
- use Illuminate\Auth\AuthenticationException;
- use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Session\TokenMismatchException;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Validation\ValidationException;
- use Symfony\Component\HttpFoundation\Response;
- use Throwable;
- class Handler
- {
- public function handle($request, Closure $next)
- {
- $response = $next($request);
- if ($response->exception)
- return $this->render($request, $response->exception);
- return $response;
- }
- public function render($request, Throwable $e): JsonResponse
- {
- $code = $e->getCode();
- $message = $e->getMessage();
- $status = Response::HTTP_INTERNAL_SERVER_ERROR;
- // CSRF 跨站请求伪造
- if ($e instanceof TokenMismatchException) {
- $status = 419;
- }
- if ($e instanceof AuthenticationException) {
- //Unauthenticated.
- $status = Response::HTTP_UNAUTHORIZED;
- $message = '登录超时!';
- }
- // 表单验证
- if ($e instanceof ValidationException) {
- $status = Response::HTTP_UNPROCESSABLE_ENTITY;
- // $status = 200;
- }
- if ($e instanceof ApiException) {
- // $status = match ($code) {
- // Response::HTTP_UNPROCESSABLE_ENTITY => 200, // 表单验证
- // default => $code,
- // };
- $status = 200;
- // 400 错误请求
- // 401 未授权
- // 403 禁止访问
- // 409 数据冲突
- // 419 CSRF跨域伪造
- // 422 验证规则
- // 500 服务器内部错误
- }
- return response()->json(['code' => $code, 'msg' => $message], $status);
- }
- }
|