Handler.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Exceptions;
  3. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  4. use Throwable;
  5. use Exception;
  6. class Handler extends ExceptionHandler
  7. {
  8. /**
  9. * A list of the exception types that are not reported.
  10. *
  11. * @var array<int, class-string<Throwable>>
  12. */
  13. protected $dontReport = [
  14. ApiException::class,
  15. ];
  16. /**
  17. * A list of the inputs that are never flashed for validation exceptions.
  18. *
  19. * @var array<int, string>
  20. */
  21. protected $dontFlash = [
  22. 'current_password',
  23. 'password',
  24. 'password_confirmation',
  25. ];
  26. /**
  27. * @param Throwable $e
  28. * @return void
  29. * @throws Throwable
  30. */
  31. public function report(Throwable $e)
  32. {
  33. $appEnv = env('APP_ENV', 'production');
  34. $appName = env('APP_NAME', '未设置项目名');
  35. if ($appEnv === 'production' && $this->shouldReport($e)) {
  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. 项目:$appName [$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. * Register the exception handling callbacks for the application.
  62. *
  63. * @return void
  64. */
  65. public function register()
  66. {
  67. $this->reportable(function (Throwable $e) {
  68. //
  69. });
  70. $this->renderable(function(Exception $e, $request) {
  71. return $this->handleException($request, $e);
  72. });
  73. }
  74. private function handleException($request, Exception $e)
  75. {
  76. if ($e instanceof ApiException) {
  77. $data = [
  78. 'code' => $e->getCode(),
  79. 'msg' => $e->getMessage(),
  80. 'data' => (Object)[]
  81. ];
  82. return response()->json($data);
  83. }
  84. return null;
  85. }
  86. }