ExceptionHandler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace app\common\exception;
  3. use think\Log;
  4. use think\exception\Handle;
  5. use think\exception\DbException;
  6. use Exception;
  7. /**
  8. * 重写Handle的render方法,实现自定义异常消息
  9. * Class ExceptionHandler
  10. * @package app\common\library\exception
  11. */
  12. class ExceptionHandler extends Handle
  13. {
  14. private $code;
  15. private $message;
  16. /**
  17. * 输出异常信息
  18. * @param Exception $e
  19. * @return \think\Response|\think\response\Json
  20. */
  21. public function render(Exception $e)
  22. {
  23. if ($e instanceof BaseException) {
  24. $this->code = $e->code;
  25. $this->message = $e->message;
  26. } else {
  27. if (config('app_debug')) {
  28. return parent::render($e);
  29. }
  30. $this->code = 0;
  31. $this->message = $e->getMessage() ?: '很抱歉,服务器内部错误';
  32. $this->recordErrorLog($e);
  33. }
  34. return json(['msg' => $this->message, 'code' => $this->code]);
  35. }
  36. /**
  37. * Report or log an exception.
  38. *
  39. * @param \Exception $exception
  40. * @return void
  41. */
  42. public function report(Exception $exception)
  43. {
  44. // 不使用内置的方式记录异常日志
  45. }
  46. /**
  47. * 将异常写入日志
  48. * @param Exception $e
  49. */
  50. private function recordErrorLog(Exception $e)
  51. {
  52. $data = [
  53. 'file' => $e->getFile(),
  54. 'line' => $e->getLine(),
  55. 'message' => $this->getMessage($e),
  56. 'code' => $this->getCode($e),
  57. 'TraceAsString' => $e->getTraceAsString()
  58. ];
  59. // 如果是mysql报错, 则记录Error SQL
  60. if ($e instanceof DbException) {
  61. $data['TraceAsString'] = "[Error SQL]: " . $e->getData()['Database Status']['Error SQL'];
  62. }
  63. // 日志标题
  64. $log = "[{$data['code']}]{$data['message']} [{$data['file']}:{$data['line']}]";
  65. // 错误trace
  66. $log .= "\r\n{$data['TraceAsString']}";
  67. Log::record($log, 'error');
  68. }
  69. }