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


Posted in PHP onOctober 16, 2019

现在谁不开发接口的呢?但是在接口开发过程中,报错误异常后居然返回错误的信息依然是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;

异常处理类:

<?php

 namespace app\common\exception;


 use Exception;
 use think\exception\ErrorException;
 use think\exception\Handle;
 use think\exception\HttpException;
 use think\console\Output;
 use think\Container;
 use think\Response;


 class JsonException extends Handle
 {
  protected $render;
  protected $ignoreReport = [
   '\\think\\exception\\HttpException',
  ];

  public function setRender($render)
  {
   $this->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的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
php中常用编辑器推荐
Jan 02 PHP
php上的memcache和memcached两个pecl库
Mar 29 PHP
在php和MySql中计算时间差的方法
Apr 22 PHP
PHP面向对象法则
Feb 23 PHP
php教程 插件机制在PHP中实现方案
Nov 02 PHP
php的array数组和使用实例简明教程(容易理解)
Mar 20 PHP
详解PHP中的mb_detect_encoding函数使用方法
Aug 18 PHP
PHP实现微信发红包程序
Aug 24 PHP
php面向对象与面向过程两种方法给图片添加文字水印
Aug 26 PHP
Laravel中的chunk组块结果集处理与注意问题
Aug 15 PHP
PHP registerXPathNamespace()函数讲解
Feb 03 PHP
PHP实现字符串大小写转函数的功能实例
Feb 06 PHP
PHP 代码简洁之道(小结)
Oct 16 #PHP
解决tp5在nginx下修改配置访问的问题
Oct 16 #PHP
Laravel6.2中用于用户登录的新密码确认流程详解
Oct 16 #PHP
PHP实现15位身份证号转18位的方法分析
Oct 16 #PHP
laravel unique验证、确认密码confirmed验证以及密码修改验证的方法
Oct 16 #PHP
解决thinkPHP 5 nginx 部署时,只跳转首页的问题
Oct 16 #PHP
详解将数据从Laravel传送到vue的四种方式
Oct 16 #PHP
You might like
特转载一高手总结PHP学习资源和链接.
2006/12/05 PHP
asp和php下textarea提交大量数据发生丢失的解决方法
2008/01/20 PHP
PHP判断文章里是否有图片的简单方法
2014/07/26 PHP
php使用str_replace实现输入框回车替换br的方法
2014/11/24 PHP
PHP基于timestamp和nonce实现的防止重放攻击方案分析
2019/07/26 PHP
PHP中Session ID的实现原理实例分析
2019/08/17 PHP
laravel执行php artisan migrate报错的解决方法
2019/10/09 PHP
制作特殊字的脚本
2006/06/26 Javascript
由prototype_1.3.1进入javascript殿堂-类的初探
2006/11/06 Javascript
一样的table?不一样的table(可编辑状态table)
2012/09/19 Javascript
JQuery插入DOM节点的方法
2015/06/11 Javascript
JS组件Bootstrap Table使用方法详解
2016/02/02 Javascript
JS Canvas定时器模拟动态加载动画
2016/09/17 Javascript
微信小程序 生命周期函数详解
2017/05/24 Javascript
使用JavaScript实现点击循环切换图片效果
2017/09/03 Javascript
JavaScript实现离开页面前提示功能【附jQuery实现方法】
2017/09/26 jQuery
js实现rem自动匹配计算font-size的示例
2017/11/18 Javascript
微信小程序chooseImage的用法(从本地相册选择图片或使用相机拍照)
2018/08/22 Javascript
layer.confirm()右边按钮实现href的例子
2019/09/27 Javascript
[43:43]完美世界DOTA2联赛PWL S2 FTD.C vs Rebirth 第一场 11.22
2020/11/24 DOTA
linux系统使用python监控apache服务器进程脚本分享
2014/01/15 Python
Flask框架学习笔记(一)安装篇(windows安装与centos安装)
2014/06/25 Python
python3实现的zip格式压缩文件夹操作示例
2019/08/17 Python
python logging设置level失败的解决方法
2020/02/19 Python
Python使用jpype模块调用jar包过程解析
2020/07/29 Python
一款css实现的鼠标经过按钮的特效
2014/09/11 HTML / CSS
教师评优事迹材料
2014/01/10 职场文书
公司行政专员岗位职责
2014/08/24 职场文书
助学贷款贫困证明
2014/09/23 职场文书
银行招聘自荐信
2015/03/06 职场文书
给男朋友的道歉短信
2015/05/12 职场文书
子女赡养老人协议书
2016/03/23 职场文书
2016大学生诚信考试承诺书
2016/03/25 职场文书
Python离线安装openpyxl模块的步骤
2021/03/30 Python
教你如何使用Python开发一个钉钉群应答机器人
2021/06/21 Python
详解Oracle数据库中自带的所有表结构(sql代码)
2021/11/20 Oracle