ExceptionHandler.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\common\exception;
  10. use think\exception\Handle;
  11. use think\Log;
  12. use Exception;
  13. /**
  14. * 重写Handle的render方法,实现自定义异常消息
  15. * Class ExceptionHandler
  16. * @package app\common\library\exception
  17. */
  18. class ExceptionHandler extends Handle
  19. {
  20. private $code;
  21. private $message;
  22. /**
  23. * 输出异常信息
  24. * @param Exception $e
  25. * @return \think\Response|\think\response\Json
  26. */
  27. public function render(Exception $e)
  28. {
  29. if ($e instanceof BaseException) {
  30. $this->code = $e->code;
  31. $this->message = $e->message;
  32. } else {
  33. if (config('app_debug')) {
  34. return parent::render($e);
  35. }
  36. $this->code = 0;
  37. $this->message = $e->getMessage() ?: '很抱歉,服务器内部错误';
  38. $this->recordErrorLog($e);
  39. }
  40. return json(['msg' => $this->message, 'code' => $this->code]);
  41. }
  42. /**
  43. * 将异常写入日志
  44. * @param Exception $e
  45. */
  46. private function recordErrorLog(Exception $e)
  47. {
  48. Log::record($e->getMessage(), 'error');
  49. Log::record($e->getTraceAsString(), 'error');
  50. }
  51. }