ExceptionHandle.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace app\api\library;
  3. use app\UserException;
  4. use Exception;
  5. use think\db\exception\DataNotFoundException;
  6. use think\db\exception\ModelNotFoundException;
  7. use think\exception\Handle;
  8. /**
  9. * 自定义API模块的错误显示
  10. */
  11. class ExceptionHandle extends Handle
  12. {
  13. public function render(Exception $e)
  14. {
  15. // 在生产环境下返回code信息
  16. //if (!\think\Config::get('app_debug')) {
  17. if(request()->isAjax()) {
  18. $statuscode = $code = 0;
  19. //$msg = 'An error occurred';
  20. $msg = $e->getMessage();
  21. // 验证异常
  22. if ($e instanceof \think\exception\ValidateException) {
  23. $code = 0;
  24. $statuscode = 200;
  25. $msg = $e->getError();
  26. }
  27. // Http异常
  28. if ($e instanceof \think\exception\HttpException) {
  29. $statuscode = $code = $e->getStatusCode();
  30. }
  31. if ($e instanceof UserException) {
  32. $code = 0;
  33. $msg = $e->getMessage();
  34. $statuscode = 200;
  35. }
  36. if ($e instanceof ModelNotFoundException) {
  37. $msg = '查找的数据不存在';
  38. }
  39. return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null], $statuscode);
  40. }
  41. //}
  42. //其它此交由系统处理
  43. return parent::render($e);
  44. }
  45. }