Handler.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Dcat\Admin\Exception;
  3. use Dcat\Admin\Contracts\ExceptionHandler;
  4. use Dcat\Admin\Support\Helper;
  5. use Illuminate\Http\Exceptions\HttpResponseException;
  6. use Illuminate\Support\MessageBag;
  7. use Illuminate\Support\ViewErrorBag;
  8. class Handler implements ExceptionHandler
  9. {
  10. /**
  11. * 处理异常.
  12. *
  13. * @param \Throwable $e
  14. * @return array|string|void
  15. */
  16. public function handle(\Throwable $e)
  17. {
  18. if ($e instanceof HttpResponseException) {
  19. throw $e;
  20. }
  21. $this->report($e);
  22. return $this->render($e);
  23. }
  24. /**
  25. * 显示异常信息.
  26. *
  27. * @param \Throwable $exception
  28. * @return array|string|void
  29. *
  30. * @throws \Throwable
  31. */
  32. public function render(\Throwable $exception)
  33. {
  34. if (config('app.debug')) {
  35. throw $exception;
  36. }
  37. if (Helper::isAjaxRequest()) {
  38. return;
  39. }
  40. $error = new MessageBag([
  41. 'type' => get_class($exception),
  42. 'message' => $exception->getMessage(),
  43. 'file' => $exception->getFile(),
  44. 'line' => $exception->getLine(),
  45. 'trace' => $this->replaceBasePath($exception->getTraceAsString()),
  46. ]);
  47. $errors = new ViewErrorBag();
  48. $errors->put('exception', $error);
  49. return view('admin::partials.exception', compact('errors'))->render();
  50. }
  51. /**
  52. * 上报异常信息.
  53. *
  54. * @param \Throwable $e
  55. */
  56. public function report(\Throwable $e)
  57. {
  58. report($e);
  59. }
  60. /**
  61. * @param string $path
  62. * @return mixed
  63. */
  64. protected function replaceBasePath(string $path)
  65. {
  66. return str_replace(
  67. str_replace('\\', '/', base_path().'/'),
  68. '',
  69. str_replace('\\', '/', $path)
  70. );
  71. }
  72. }