本篇文章給大家分享的是有關怎么在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自定義全局異常處理,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。