侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Thinkphp 在api开发中异常返回依然是html的解决方式

ThinkPHP  /  管理员 发布于 8年前   225

现在谁不开发接口的呢?但是在接口开发过程中,报错误异常后居然返回错误的信息依然是html信息!TP官方也不知道为啥不添加,说好的为接口而生,我的解决方案也很简单,把系统的异常处理类复制出来,去掉模板相关,直接以json方式输出

下面是解决方案:

1:按照TP扩展异常的方式引用这个文件

https://www.kancloud.cn/manual/thinkphp5_1/354092

// 判断默认输出类型// $app 是配置数组if ($app['default_return_type'] == 'json') { // 异常处理handle类 留空使用 \think\exception\Handle $app['exception_handle'] = '\\app\\common\\exception\\JsonException';}return $app;

异常处理类:

render = $render;  }  /**  * Report or log an exception.  *  * @access public  * @param \Exception $exception  * @return void  */  public function report(Exception $exception)  {   if (!$this->isIgnoreReport($exception)) {   // 收集异常数据   if (Container::get('app')->isDebug()) {    $data = [     'file' => $exception->getFile(),     'line' => $exception->getLine(),     'message' => $this->getMessage($exception),     'code' => $this->getCode($exception),    ];    $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]";   } else {    $data = [     'code' => $this->getCode($exception),     'message' => $this->getMessage($exception),    ];    $log = "[{$data['code']}]{$data['message']}";   }   if (Container::get('app')->config('log.record_trace')) {    $log .= "\r\n" . $exception->getTraceAsString();   }   Container::get('log')->record($log, 'error');   }  }  protected function isIgnoreReport(Exception $exception)  {   foreach ($this->ignoreReport as $class) {   if ($exception instanceof $class) {    return true;   }   }   return false;  }  /**  * Render an exception into an HTTP response.  *  * @access public  * @param \Exception $e  * @return Response  */  public function render(Exception $e)  {   if ($this->render && $this->render instanceof \Closure) {   $result = call_user_func_array($this->render, [$e]);   if ($result) {    return $result;   }   }   if ($e instanceof HttpException) {   return $this->renderHttpException($e);   } else {   return $this->convertExceptionToResponse($e);   }  }  /**  * @access public  * @param Output $output  * @param Exception $e  */  public function renderForConsole(Output $output, Exception $e)  {   if (Container::get('app')->isDebug()) {   $output->setVerbosity(Output::VERBOSITY_DEBUG);   }   $output->renderException($e);  }  /**  * @access protected  * @param HttpException $e  * @return Response  */  protected function renderHttpException(HttpException $e)  {   $status = $e->getStatusCode();   $template = Container::get('app')->config('http_exception_template');   if (!Container::get('app')->isDebug() && !empty($template[$status])) {   return Response::create($e, 'json', $status);   } else {   return $this->convertExceptionToResponse($e);   }  }  /**  * @access protected  * @param Exception $exception  * @return Response  */  protected function convertExceptionToResponse(Exception $exception)  {   // 收集异常数据   if (Container::get('app')->isDebug()) {   // 调试模式,获取详细的错误信息   $data = [    'name' => get_class($exception),    'file' => $exception->getFile(),    'line' => $exception->getLine(),    'message' => $this->getMessage($exception),    'trace' => $exception->getTrace(),    'code' => $this->getCode($exception),    'source' => $this->getSourceCode($exception),    'datas' => $this->getExtendData($exception),    'tables' => [     'GET Data'    => $_GET,     'POST Data'    => $_POST,     'Files'     => $_FILES,     'Cookies'    => $_COOKIE,     'Session'    => isset($_SESSION) ? $_SESSION : [],     'Server/Request Data' => $_SERVER,     'Environment Variables' => $_ENV,     'ThinkPHP Constants' => $this->getConst(),    ],   ];   } else {   // 部署模式仅显示 Code 和 Message   $data = [    'code' => $this->getCode($exception),    'message' => $this->getMessage($exception),   ];   if (!Container::get('app')->config('show_error_msg')) {    // 不显示详细错误信息    $data['message'] = Container::get('app')->config('error_message');   }   }   //保留一层   while (ob_get_level() > 1) {   ob_end_clean();   }   $data['echo'] = ob_get_clean();   $response = Response::create($data, 'json');   if ($exception instanceof HttpException) {   $statusCode = $exception->getStatusCode();   $response->header($exception->getHeaders());   }   if (!isset($statusCode)) {   $statusCode = 500;   }   $response->code($statusCode);   return $response;  }  /**  * 获取错误编码  * ErrorException则使用错误级别作为错误编码  * @access protected  * @param \Exception $exception  * @return integer    错误编码  */  protected function getCode(Exception $exception)  {   $code = $exception->getCode();   if (!$code && $exception instanceof ErrorException) {   $code = $exception->getSeverity();   }   return $code;  }  /**  * 获取错误信息  * ErrorException则使用错误级别作为错误编码  * @access protected  * @param \Exception $exception  * @return string    错误信息  */  protected function getMessage(Exception $exception)  {   $message = $exception->getMessage();   if (PHP_SAPI == 'cli') {   return $message;   }   $lang = Container::get('lang');   if (strpos($message, ':')) {   $name = strstr($message, ':', true);   $message = $lang->has($name) ? $lang->get($name) . strstr($message, ':') : $message;   } elseif (strpos($message, ',')) {   $name = strstr($message, ',', true);   $message = $lang->has($name) ? $lang->get($name) . ':' . substr(strstr($message, ','), 1) : $message;   } elseif ($lang->has($message)) {   $message = $lang->get($message);   }   return $message;  }  /**  * 获取出错文件内容  * 获取错误的前9行和后9行  * @access protected  * @param \Exception $exception  * @return array     错误文件内容  */  protected function getSourceCode(Exception $exception)  {   // 读取前9行和后9行   $line = $exception->getLine();   $first = ($line - 9 > 0) ? $line - 9 : 1;   try {   $contents = file($exception->getFile());   $source = [    'first' => $first,    'source' => array_slice($contents, $first - 1, 19),   ];   } catch (Exception $e) {   $source = [];   }   return $source;  }  /**  * 获取异常扩展信息  * 用于非调试模式html返回类型显示  * @access protected  * @param \Exception $exception  * @return array     异常类定义的扩展数据  */  protected function getExtendData(Exception $exception)  {   $data = [];   if ($exception instanceof \think\Exception) {   $data = $exception->getData();   }   return $data;  }  /**  * 获取常量列表  * @access private  * @return array 常量列表  */  private static function getConst()  {   $const = get_defined_constants(true);   return isset($const['user']) ? $const['user'] : [];  } }

以上这篇Thinkphp 在api开发中异常返回依然是html的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的文章:

  • thinkphp5使html5实现动态跳转的例子
  • php中try catch捕获异常实例详解


  • 上一条:
    TP5框架请求响应参数实例分析
    下一条:
    解决tp5在nginx下修改配置访问的问题
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • thinkphp + mongodb项目中数据加载慢问题分析及解决(0个评论)
    • thinkphp6框架中封装redis操作类(0个评论)
    • thinkphp6框架中实现定时任务功能流程步骤(0个评论)
    • Thinkphp5.1框架中实现Session+Redis会话共享流程步骤(0个评论)
    • TP5框架版本5.0.10安全漏洞根据官方补丁修复,也是本站安全漏洞修复(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-12
    • 2018-01
    • 2018-02
    • 2020-03
    • 2021-07
    • 2021-12
    • 2022-05
    • 2022-06
    • 2022-09
    • 2023-01
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客