Handler.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Exceptions;
  3. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  4. use Illuminate\Validation\ValidationException;
  5. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  6. use Throwable;
  7. class Handler extends ExceptionHandler
  8. {
  9. /**
  10. * A list of the exception types that are not reported.
  11. *
  12. * @var array
  13. */
  14. protected $dontReport = [
  15. //
  16. ];
  17. /**
  18. * A list of the inputs that are never flashed for validation exceptions.
  19. *
  20. * @var array
  21. */
  22. protected $dontFlash = [
  23. 'current_password',
  24. 'password',
  25. 'password_confirmation',
  26. ];
  27. /**
  28. * Register the exception handling callbacks for the application.
  29. *
  30. * @return void
  31. */
  32. public function register()
  33. {
  34. $this->reportable(function (Throwable $e) {
  35. //
  36. });
  37. }
  38. /**
  39. * @create JianJia.Zhou<z656123456@gmail.com>
  40. * @param \Illuminate\Http\Request $request
  41. * @param Throwable $exception
  42. * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
  43. */
  44. public function render($request, Throwable $exception)
  45. {
  46. //如果错误是 ValidationException 的一个实例,说明是一个验证的错误
  47. if ($exception instanceof ValidationException) {
  48. return out(null, 10000, array_values($exception->errors())[0][0]);
  49. }
  50. // 需要登录
  51. if ($exception instanceof UnauthorizedHttpException) {
  52. return out(null, 401, $exception->getMessage());
  53. }
  54. // 其他异常
  55. if ($exception instanceof Exception){
  56. $msg = $exception->getMessage();
  57. $out = json_decode($msg, true);
  58. //\Log::info('异常内容');
  59. //\Log::info($exception);
  60. return out($out['data'] ?? null, $out['code'] ?? 500, $out['message'] ?? $msg);
  61. }
  62. if (env('APP_DEBUG')) {
  63. return out(null, 500, $exception->getMessage());
  64. }
  65. return out(null, 500, '系统错误,请稍后重试');
  66. }
  67. }