ExceptionHandle.php 1.7 KB

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