Handler.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }
  40. if ($e instanceof ApiException) {
  41. // // 400 错误请求
  42. // // 401 未授权
  43. // // 403 禁止访问
  44. // // 409 数据冲突
  45. // 419 CSRF跨域伪造
  46. // // 422 验证规则
  47. // // 500 服务器内部错误
  48. $status = $code;
  49. }
  50. return response()->json(['code' => $status, 'message' => $message], $status);
  51. }
  52. }