laravel框架 api自定義全域性異常處理方法
阿新 • • 發佈:2020-11-19
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自定義全域性異常處理方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援碼農教程。