Handler.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  5. use Illuminate\Validation\ValidationException;
  6. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  7. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  8. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  9. class Handler extends ExceptionHandler
  10. {
  11. /**
  12. * A list of the exception types that are not reported.
  13. *
  14. * @var array
  15. */
  16. protected $dontReport = [
  17. //
  18. ];
  19. /**
  20. * A list of the inputs that are never flashed for validation exceptions.
  21. *
  22. * @var array
  23. */
  24. protected $dontFlash = [
  25. 'password',
  26. 'password_confirmation',
  27. ];
  28. /**
  29. * Report or log an exception.
  30. *
  31. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
  32. *
  33. * @param \Exception $exception
  34. * @return void
  35. */
  36. public function report(Exception $exception)
  37. {
  38. parent::report($exception);
  39. }
  40. public function render($request, Exception $exception)
  41. {
  42. if ($exception instanceof ValidationException) {
  43. // return response(['error' => array_first(array_collapse($exception->errors()))], 400);
  44. return showJson(102, array_first(array_collapse($exception->errors())));
  45. }
  46. if ($exception instanceof UnauthorizedHttpException) {
  47. return response($exception->getMessage(), 401);
  48. }
  49. // 权限拦截器
  50. if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
  51. // 你的代码在这 ...
  52. return showJson(102, 1002, ['msg' => $exception->getMessage()]);
  53. }
  54. // 如果不被允许的路由
  55. if ($exception instanceof MethodNotAllowedHttpException || $exception instanceof NotFoundHttpException) {
  56. if (!($request->ajax() || $request->wantsJson())) {
  57. return showJson(102, '路由不存在');
  58. }
  59. }
  60. return parent::render($request, $exception);
  61. }
  62. }