Handler.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Auth\AuthenticationException;
  5. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  6. use Illuminate\Session\TokenMismatchException;
  7. class Handler extends ExceptionHandler
  8. {
  9. /**
  10. * A list of the exception types that should not be reported.
  11. *
  12. * @var array
  13. */
  14. protected $dontReport = [
  15. \Illuminate\Auth\AuthenticationException::class,
  16. \Illuminate\Auth\Access\AuthorizationException::class,
  17. \Symfony\Component\HttpKernel\Exception\HttpException::class,
  18. \Illuminate\Database\Eloquent\ModelNotFoundException::class,
  19. \Illuminate\Session\TokenMismatchException::class,
  20. \Illuminate\Validation\ValidationException::class,
  21. ];
  22. /**
  23. * Report or log an exception.
  24. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
  25. *
  26. * @param Exception $exception
  27. *
  28. * @throws Exception
  29. */
  30. public function report(Exception $exception)
  31. {
  32. parent::report($exception);
  33. }
  34. /**
  35. * Render an exception into an HTTP response.
  36. *
  37. * @param \Illuminate\Http\Request $request
  38. * @param \Exception $exception
  39. *
  40. * @return \Illuminate\Http\Response
  41. */
  42. public function render($request, Exception $exception)
  43. {
  44. if (config('app.debug')) {
  45. \Log::info("请求导致异常的地址:" . $request->fullUrl() . ",请求IP:" . $request->getClientIp());
  46. return parent::render($request, $exception);
  47. }
  48. // 捕获身份校验异常
  49. if ($exception instanceof AuthenticationException) {
  50. if ($request->ajax()) {
  51. return response()->json(['status' => 'fail', 'data' => '', 'message' => 'Unauthorized']);
  52. } else {
  53. return response()->view('error.404');
  54. }
  55. }
  56. // 捕获CSRF异常
  57. if ($exception instanceof TokenMismatchException) {
  58. if ($request->ajax()) {
  59. return response()->json(['status' => 'fail', 'data' => '', 'message' => trans('404.csrf_title')]);
  60. } else {
  61. return response()->view('error.csrf');
  62. }
  63. }
  64. return response()->view('error.404');
  65. }
  66. /**
  67. * Convert an authentication exception into an unauthenticated response.
  68. *
  69. * @param \Illuminate\Http\Request $request
  70. * @param \Illuminate\Auth\AuthenticationException $exception
  71. *
  72. * @return \Illuminate\Http\Response
  73. */
  74. protected function unauthenticated($request, AuthenticationException $exception)
  75. {
  76. if ($request->expectsJson()) {
  77. return response()->json(['error' => 'Unauthenticated.'], 401);
  78. }
  79. return redirect()->guest(route('login'));
  80. }
  81. }