Handler.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Exceptions;
  3. use Closure;
  4. use Exception;
  5. use Illuminate\Auth\AuthenticationException;
  6. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  7. use Illuminate\Http\JsonResponse;
  8. use Illuminate\Session\TokenMismatchException;
  9. use Illuminate\Support\Facades\Auth;
  10. use Illuminate\Validation\ValidationException;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Throwable;
  13. class Handler
  14. {
  15. public function handle($request, Closure $next)
  16. {
  17. $response = $next($request);
  18. if ($response->exception)
  19. return $this->render($request, $response->exception);
  20. return $response;
  21. }
  22. public function render($request, Throwable $e): JsonResponse
  23. {
  24. $code = $e->getCode();
  25. $message = $e->getMessage();
  26. $status = Response::HTTP_INTERNAL_SERVER_ERROR;
  27. // CSRF 跨站请求伪造
  28. if ($e instanceof TokenMismatchException) {
  29. $status = 419;
  30. }
  31. if ($e instanceof AuthenticationException) {
  32. //Unauthenticated.
  33. $status = Response::HTTP_UNAUTHORIZED;
  34. $message = '登录超时!';
  35. }
  36. // 表单验证
  37. if ($e instanceof ValidationException) {
  38. $status = Response::HTTP_UNPROCESSABLE_ENTITY;
  39. // $status = 200;
  40. }
  41. if ($e instanceof ApiException) {
  42. $status = match ($code) {
  43. Response::HTTP_UNPROCESSABLE_ENTITY => 200, // 表单验证
  44. default => $code,
  45. };
  46. // 400 错误请求
  47. // 401 未授权
  48. // 403 禁止访问
  49. // 409 数据冲突
  50. // 419 CSRF跨域伪造
  51. // 422 验证规则
  52. // 500 服务器内部错误
  53. }
  54. return response()->json(['code' => $code, 'message' => $message], $status);
  55. }
  56. }