ExceptionHandle.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace app\api\library;
  3. use Exception;
  4. use think\exception\Handle;
  5. /**
  6. * 自定义API模块的错误显示
  7. */
  8. class ExceptionHandle extends Handle
  9. {
  10. public function render(Exception $e)
  11. {
  12. //return parent::render($e);
  13. $statuscode = $code = 500;
  14. $msg = $e->getMessage();
  15. // 验证异常
  16. if ($e instanceof \think\exception\ValidateException) {
  17. $code = 0;
  18. $statuscode = 200;
  19. $msg = $e->getError();
  20. }
  21. // Http异常
  22. if ($e instanceof \think\exception\HttpException) {
  23. $statuscode = $code = $e->getStatusCode();
  24. $msg = $e->getMessage();
  25. }
  26. $result = ['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null];
  27. //记录app异常返回结果
  28. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  29. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($result)]);
  30. }
  31. return json($result, $statuscode);
  32. }
  33. }