ExceptionHandle.php 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace app\api\library;
  3. use Exception;
  4. use think\exception\Handle;
  5. use think\Log;
  6. use app\common\exception\BusinessException;
  7. /**
  8. * 自定义API模块的错误显示
  9. * 统一处理API异常和服务层异常
  10. */
  11. class ExceptionHandle extends Handle
  12. {
  13. public function render(Exception $e)
  14. {
  15. // 业务异常:开发和生产环境都返回json
  16. if ($e instanceof BusinessException) {
  17. $code = 0;
  18. $statuscode = 200;
  19. $msg = $e->getMessage() ?: '业务处理失败';
  20. Log::record([
  21. 'exception' => 'BusinessException',
  22. 'custom_error_code' => $e->getErrorCode(),
  23. 'message' => $e->getMessage(),
  24. 'error_data' => $e->getErrorData(),
  25. 'file' => $e->getFile(),
  26. 'line' => $e->getLine(),
  27. ], 'info');
  28. return json([
  29. 'code' => $code,
  30. 'msg' => $msg,
  31. 'time' => time(),
  32. 'data' => null
  33. ], $statuscode);
  34. }
  35. // 在生产环境下返回code信息
  36. if (!\think\Config::get('app_debug')) {
  37. $statuscode = $code = 500;
  38. $msg = 'An error occurred';
  39. // 验证异常
  40. if ($e instanceof \think\exception\ValidateException) {
  41. $code = 0;
  42. $statuscode = 200;
  43. $msg = $e->getError();
  44. }
  45. // Http异常
  46. elseif ($e instanceof \think\exception\HttpException) {
  47. $statuscode = $code = $e->getStatusCode();
  48. $msg = $e->getMessage() ?: 'Http Error';
  49. }
  50. // 自定义业务异常(与验证异常保持一致的返回格式)
  51. elseif ($e instanceof BusinessException) {
  52. $code = 0; // 业务异常统一返回code=0,与验证异常一致
  53. $statuscode = 200; // HTTP状态码为200
  54. $msg = $e->getMessage() ?: '业务处理失败';
  55. // 记录业务异常日志(便于调试,包含自定义错误码)
  56. Log::record([
  57. 'exception' => 'BusinessException',
  58. 'custom_error_code' => $e->getErrorCode(), // 记录自定义错误码用于调试
  59. 'message' => $e->getMessage(),
  60. 'error_data' => $e->getErrorData(),
  61. 'file' => $e->getFile(),
  62. 'line' => $e->getLine(),
  63. ], 'info'); // 业务异常用info级别记录
  64. }
  65. // 其他异常(包括服务层的普通Exception)
  66. elseif ($e instanceof \Exception) {
  67. $code = 0; // 普通异常统一返回code=0
  68. $statuscode = 200; // HTTP状态码为200
  69. $msg = $e->getMessage() ?: '业务处理失败';
  70. // 记录服务层异常日志(便于调试)
  71. Log::record([
  72. 'exception' => get_class($e),
  73. 'message' => $e->getMessage(),
  74. 'file' => $e->getFile(),
  75. 'line' => $e->getLine(),
  76. 'trace' => $e->getTraceAsString()
  77. ], 'error');
  78. }
  79. return json([
  80. 'code' => $code,
  81. 'msg' => $msg,
  82. 'time' => time(),
  83. 'data' => null
  84. ], $statuscode);
  85. }
  86. // 开发环境下交由系统处理
  87. return parent::render($e);
  88. }
  89. }