api接口返回为异常是html情况的问题怎么处理
Admin 2022-06-21 群英技术资讯 1682 次浏览
关于“api接口返回为异常是html情况的问题怎么处理”的知识有一些人不是很理解,对此小编给大家总结了相关内容,具有一定的参考借鉴价值,而且易于学习与理解,希望能对大家有所帮助,有这个方面学习需要的朋友就继续往下看吧。现在谁不开发接口的呢?但是在接口开发过程中,报错误异常后居然返回错误的信息依然是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'] : [];
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
今天小编就为大家分享一篇关于PHP count_chars()函数讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
php之laravel中自定义模板命令:1、创建ToJsServiceProvider;2、ToJs方法主要是对数组的操作;3、声明facade;4、在config数组添加serviceProvider;5、方便调用可以在写helper。
php数组添加元素:1、array_push()函数将数组视为栈,将传入的变量压入数组的末尾,数组变量增加、长度增加。2、arr[]直接添加元素。3、array_fill()用给定的值填充数组。
大家在调试Hyperf的时候,可能总需要做一些服务的重启,重新点击postman的接口请求按钮,查看调试的结果是否正常,这篇文章就是教大家如何在PhpStorm中完成这一系列的操作。
定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新 能够便利地创建查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008