ExceptionHandle.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace app\sub\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. protected $ignoreReport = [
  14. '\\think\\exception\\HttpException',
  15. UserException::class,
  16. ];
  17. public function render(Exception $e)
  18. {
  19. // 在生产环境下返回code信息
  20. //if (!\think\Config::get('app_debug')) {
  21. if(request()->isAjax() || strpos(request()->header('Accept'),'/json')!==false) {
  22. $statuscode = $code = 0;
  23. //$msg = 'An error occurred';
  24. $msg = $e->getMessage();
  25. // 验证异常
  26. if ($e instanceof \think\exception\ValidateException) {
  27. $code = 0;
  28. $statuscode = 200;
  29. $msg = $e->getError();
  30. }
  31. // Http异常
  32. if ($e instanceof \think\exception\HttpException) {
  33. $statuscode = $code = $e->getStatusCode();
  34. }
  35. if ($e instanceof UserException) {
  36. $code = 0;
  37. $msg = $e->getMessage();
  38. $statuscode = 200;
  39. }
  40. if ($e instanceof ModelNotFoundException) {
  41. $msg = '查找的数据不存在';
  42. }
  43. return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null], $statuscode);
  44. }
  45. //}
  46. //其它此交由系统处理
  47. return parent::render($e);
  48. }
  49. }