ExceptionHandler.php 1.2 KB

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