laravel框架 api自定义全局异常处理方法
更新时间:2019年10月11日 16:45:47 作者:Miss_shy
今天小编就为大家分享一篇laravel框架 api自定义全局异常处理方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
api返回实现
$result = User::find($id);
if(empty($result)){
throw new ApiException('获取失败');
}
else{
return json_decode($result);
}
api返回信息
{
"msg": "",
"data": "获取失败",
"status": 0
}
1,添加异常类
namespace App\Exceptions;
class ApiException extends \Exception
{
function _construct($msg='')
{
parent::_construct($msg);
}
}
2,修改laravel异常类u。。。
namespace App\Exceptions;
public function render($request, Exception $e)
{
if ($e instanceof ApiException){
$result = [
"msg" => "",
"data"=>$e->getMessage(),
"status"=>0
];
return response()->json($result);
}
return parent::render($request, $e);
考虑开发配置时
public function render($request, Exception $e)
{
if(config('app.debug')){
return parent::render($request,$e);
}
return $this->handle($request,$e);
}
public function handle($request,Exception $e){
if ($e instanceof ApiException){
$result = [
"msg" => "",
"data"=>$e->getMessage(),
"status"=>0
];
return response()->json($result);
}
return parent::render($request, $e);
}
以上这篇laravel框架 api自定义全局异常处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Zend Framework入门教程之Zend_Session会话操作详解
这篇文章主要介绍了Zend Framework入门教程之Zend_Session会话操作,结合实例形式详细分析了Zend_Session会话操作的具体使用技巧,需要的朋友可以参考下2016-12-12
php reset() 函数指针指向数组中的第一个元素并输出实例代码
在php中,当我们使用next函数或end函数将数组内部针指指向数组最后一个元素的时候,如果再需要将内部指针指向第一个元素,可以使用reset() 函数来实现,本文章向大家讲解reset() 函数的基本语法及使用实例,需要的朋友可以参考下2016-11-11


最新评论