Handler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Auth\Access\AuthorizationException;
  5. use Illuminate\Database\Eloquent\ModelNotFoundException;
  6. use Illuminate\Validation\ValidationException;
  7. use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
  8. use Symfony\Component\HttpKernel\Exception\HttpException;
  9. class Handler extends ExceptionHandler
  10. {
  11. /**
  12. * A list of the exception types that should not be reported.
  13. *
  14. * @var array
  15. */
  16. protected $dontReport = [
  17. AuthorizationException::class,
  18. HttpException::class,
  19. ModelNotFoundException::class,
  20. ValidationException::class,
  21. ];
  22. /**
  23. * Report or log an exception.
  24. *
  25. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
  26. *
  27. * @param \Exception $exception
  28. * @return void
  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. * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
  40. */
  41. public function render($request, Exception $exception)
  42. {
  43. // 参数验证错误的异常,我们需要返回 400 的 http code 和一句错误信息
  44. if ($exception instanceof ValidationException) {
  45. return response()->json([ 'code'=>'4011', 'msg' => array_first(array_collapse($exception->errors()))]);
  46. }
  47. // 用户认证的异常,我们需要返回 401 的 http code 和错误信息
  48. if ($exception instanceof UnauthorizedHttpException) {
  49. return response()->json([ 'code'=>'4012', 'msg' => $exception->getMessage()]);
  50. }
  51. //token异常
  52. if($exception instanceof TokenBlacklistedException){
  53. return response()->json([ 'code'=>'4013', 'msg' => $exception->getMessage()]);
  54. }
  55. // return parent::render($request, $exception);
  56. return parent::render($request, $exception);
  57. }
  58. }