Handler.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Validation\ValidationException;
  5. use Illuminate\Auth\Access\AuthorizationException;
  6. use Illuminate\Database\Eloquent\ModelNotFoundException;
  7. use Symfony\Component\HttpKernel\Exception\HttpException;
  8. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  9. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  10. class Handler extends ExceptionHandler
  11. {
  12. /**
  13. * A list of the exception types that should not be reported.
  14. *
  15. * @var array
  16. */
  17. protected $dontReport = [
  18. AuthorizationException::class,
  19. HttpException::class,
  20. ModelNotFoundException::class,
  21. ValidationException::class,
  22. ApiException::class,
  23. ];
  24. /**
  25. * Report or log an exception.
  26. *
  27. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
  28. *
  29. * @param \Exception $e
  30. * @return void
  31. */
  32. public function report(Exception $e)
  33. {
  34. $appEnv = env('APP_ENV', 'production');
  35. if ($this->shouldReport($e) && env('APP_ENV') == 'production') {
  36. $date = date('Y-m-d H:i:s');
  37. $file = $e->getFile();
  38. $line = $e->getLine();
  39. $message = $e->getMessage();
  40. $trace = $e->getTraceAsString();
  41. $traceArr = explode('#', $trace);
  42. $traceSimple = $trace;
  43. if (is_array($traceArr)) {
  44. $traceSub = array_slice($traceArr, 0, 3);
  45. $traceSimple = implode('#', $traceSub);
  46. }
  47. $msg = <<<EOF
  48. 项目:quick_app [$appEnv]
  49. 报错时间:$date
  50. 报错文件:$file
  51. 报错行数:line $line
  52. 报错信息:$message
  53. 报错跟踪:
  54. $traceSimple
  55. EOF;
  56. sendNotice($msg);
  57. }
  58. parent::report($e);
  59. }
  60. /**
  61. * Render an exception into an HTTP response.
  62. *
  63. * @param \Illuminate\Http\Request $request
  64. * @param \Exception $e
  65. * @return \Illuminate\Http\Response
  66. */
  67. /*
  68. public function render($request, Exception $e)
  69. {
  70. return parent::render($request, $e);
  71. }
  72. */
  73. public function render($request, Exception $e)
  74. {
  75. if ($e instanceof ApiException) {
  76. $data = [
  77. 'code' => $e->getCode(),
  78. 'msg' => $e->getMessage(),
  79. 'data' => []
  80. ];
  81. return response()->json($data);
  82. }
  83. if($e instanceof ValidationException) {
  84. return response()->json([
  85. 'code' => -1,
  86. 'msg' => array_first(array_flatten($e->errors()))
  87. ]);
  88. }
  89. return parent::render($request, $e);
  90. }
  91. }