Handler.php 1.7 KB

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