ExceptionHandle.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace app;
  3. use think\exception\Handle;
  4. use think\exception\HttpResponseException;
  5. use Throwable;
  6. use think\Response;
  7. use think\exception\HttpException;
  8. /**
  9. * 应用异常处理类
  10. */
  11. class ExceptionHandle extends Handle
  12. {
  13. public function render($request, Throwable $e): Response {
  14. // 调试模式
  15. if (env('app_debug')){
  16. // Ajax请求返回JSON
  17. if ($request->isAjax()) {
  18. if ($e instanceof HttpResponseException) {
  19. return $e->getResponse();
  20. } elseif ($e instanceof HttpException) {
  21. return json(['code'=>$e->getStatusCode(),'msg'=>$e->getMessage()],$e->getStatusCode());
  22. } else {
  23. return json(['code' => 500, 'msg' => $e->getMessage(),'trace'=>$e->getTrace()],500);
  24. }
  25. }
  26. // 非Ajax请求默认处理
  27. return parent::render($request, $e);
  28. } else {
  29. if ($request->isAjax()) {
  30. return json(['code'=>500,'msg'=>'服务器异常'],500);
  31. } else {
  32. return parent::render($request, $e);
  33. }
  34. }
  35. }
  36. }