Handler.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Exceptions;
  3. use Illuminate\Auth\AuthenticationException;
  4. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  5. use Illuminate\Support\Facades\Log;
  6. use Throwable;
  7. use Illuminate\Validation\ValidationException;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  10. class Handler extends ExceptionHandler
  11. {
  12. /**
  13. * A list of the exception types that are not reported.
  14. *
  15. * @var array<int, class-string<Throwable>>
  16. */
  17. protected $dontReport = [
  18. //
  19. ];
  20. /**
  21. * A list of the inputs that are never flashed for validation exceptions.
  22. *
  23. * @var array<int, string>
  24. */
  25. protected $dontFlash = [
  26. 'current_password',
  27. 'password',
  28. 'password_confirmation',
  29. ];
  30. /**
  31. * Register the exception handling callbacks for the application.
  32. *
  33. * @return void
  34. */
  35. public function register()
  36. {
  37. $this->reportable(function (Throwable $e) {
  38. //
  39. });
  40. }
  41. // 异常处理
  42. public function report(Throwable $exception)
  43. {
  44. parent::report($exception); // 调用父类的 report 方法,记录日志
  45. }
  46. /**
  47. * Render an exception into an HTTP response.
  48. *
  49. * @param \Illuminate\Http\Request $request
  50. * @param \Throwable $exception
  51. * @return \Symfony\Component\HttpFoundation\Response
  52. */
  53. public function render($request, Throwable $exception)
  54. {
  55. // sanctum 异常处理
  56. if ($exception instanceof RouteNotFoundException || $exception instanceof AuthenticationException) {
  57. return response()->json([
  58. 'code' => 401,
  59. 'msg' => "登录已过期",
  60. ], 401);
  61. }
  62. // 捕获 NotFoundHttpException 异常并自定义处理
  63. if ($exception instanceof NotFoundHttpException) {
  64. return response()->view('errors.404', [], 404); // 返回自定义的 404 错误页面
  65. }
  66. // 捕获 ValidationException 并返回统一的 JSON 错误响应
  67. if ($exception instanceof ValidationException) {
  68. $errors = $exception->errors();
  69. return response()->json([
  70. 'code' => 0,
  71. // 'msg' => '参数校验失败',
  72. 'msg' => '参数校验失败 ' . array_keys($errors)[0] . ' - ' . reset($errors)[0],
  73. ], 422);
  74. }
  75. // 你可以在这里捕获所有的异常,进行日志记录
  76. if ($exception instanceof \Throwable) {
  77. // 记录日志
  78. Log::error($exception);
  79. // 返回统一的错误响应
  80. return response()->json(['code' => 0, 'msg' => '请求异常'], 400);
  81. }
  82. // 如果是其他类型的异常,交给父类处理
  83. return parent::render($request, $exception);
  84. }
  85. }