ApiExceptionHandle.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace app\api\library;
  3. use think\exception\Handle;
  4. use think\exception\HttpException;
  5. use think\exception\HttpResponseException;
  6. use think\exception\ValidateException;
  7. use think\Response;
  8. use Throwable;
  9. /**
  10. * 自定义API模块的错误显示
  11. */
  12. class ApiExceptionHandle extends Handle
  13. {
  14. /**
  15. * Render an exception into an HTTP response.
  16. *
  17. * @access public
  18. * @param \think\Request $request
  19. * @param Throwable $e
  20. * @return Response
  21. */
  22. public function render($request, Throwable $e): Response
  23. {
  24. // 在生产环境下返回code信息
  25. if (!$this->app->isDebug()) {
  26. if ($e instanceof HttpResponseException) {
  27. return $e->getResponse();
  28. }
  29. $statuscode = $code = 500;
  30. $msg = 'An error occurred';
  31. // 验证异常
  32. if ($e instanceof ValidateException) {
  33. $code = 0;
  34. $statuscode = 200;
  35. $msg = $e->getError();
  36. }
  37. // Http异常
  38. if ($e instanceof HttpException) {
  39. $statuscode = $code = $e->getStatusCode();
  40. }
  41. return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null], $statuscode);
  42. }
  43. //其它此交由系统处理
  44. return parent::render($request, $e);
  45. }
  46. }