Thinkphp 在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;
异常处理类:
render=$render;
}
/**
*Reportorloganexception.
*
*@accesspublic
*@param\Exception$exception
*@returnvoid
*/
publicfunctionreport(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');
}
}
protectedfunctionisIgnoreReport(Exception$exception)
{
foreach($this->ignoreReportas$class){
if($exceptioninstanceof$class){
returntrue;
}
}
returnfalse;
}
/**
*RenderanexceptionintoanHTTPresponse.
*
*@accesspublic
*@param\Exception$e
*@returnResponse
*/
publicfunctionrender(Exception$e)
{
if($this->render&&$this->renderinstanceof\Closure){
$result=call_user_func_array($this->render,[$e]);
if($result){
return$result;
}
}
if($einstanceofHttpException){
return$this->renderHttpException($e);
}else{
return$this->convertExceptionToResponse($e);
}
}
/**
*@accesspublic
*@paramOutput$output
*@paramException$e
*/
publicfunctionrenderForConsole(Output$output,Exception$e)
{
if(Container::get('app')->isDebug()){
$output->setVerbosity(Output::VERBOSITY_DEBUG);
}
$output->renderException($e);
}
/**
*@accessprotected
*@paramHttpException$e
*@returnResponse
*/
protectedfunctionrenderHttpException(HttpException$e)
{
$status=$e->getStatusCode();
$template=Container::get('app')->config('http_exception_template');
if(!Container::get('app')->isDebug()&&!empty($template[$status])){
returnResponse::create($e,'json',$status);
}else{
return$this->convertExceptionToResponse($e);
}
}
/**
*@accessprotected
*@paramException$exception
*@returnResponse
*/
protectedfunctionconvertExceptionToResponse(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'=>[
'GETData'=>$_GET,
'POSTData'=>$_POST,
'Files'=>$_FILES,
'Cookies'=>$_COOKIE,
'Session'=>isset($_SESSION)?$_SESSION:[],
'Server/RequestData'=>$_SERVER,
'EnvironmentVariables'=>$_ENV,
'ThinkPHPConstants'=>$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($exceptioninstanceofHttpException){
$statusCode=$exception->getStatusCode();
$response->header($exception->getHeaders());
}
if(!isset($statusCode)){
$statusCode=500;
}
$response->code($statusCode);
return$response;
}
/**
*获取错误编码
*ErrorException则使用错误级别作为错误编码
*@accessprotected
*@param\Exception$exception
*@returninteger错误编码
*/
protectedfunctiongetCode(Exception$exception)
{
$code=$exception->getCode();
if(!$code&&$exceptioninstanceofErrorException){
$code=$exception->getSeverity();
}
return$code;
}
/**
*获取错误信息
*ErrorException则使用错误级别作为错误编码
*@accessprotected
*@param\Exception$exception
*@returnstring错误信息
*/
protectedfunctiongetMessage(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行
*@accessprotected
*@param\Exception$exception
*@returnarray错误文件内容
*/
protectedfunctiongetSourceCode(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返回类型显示
*@accessprotected
*@param\Exception$exception
*@returnarray异常类定义的扩展数据
*/
protectedfunctiongetExtendData(Exception$exception)
{
$data=[];
if($exceptioninstanceof\think\Exception){
$data=$exception->getData();
}
return$data;
}
/**
*获取常量列表
*@accessprivate
*@returnarray常量列表
*/
privatestaticfunctiongetConst()
{
$const=get_defined_constants(true);
returnisset($const['user'])?$const['user']:[];
}
}
以上这篇Thinkphp在api开发中异常返回依然是html的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。