laravel 中自定義 api 介面的錯誤訊息
阿新 • • 發佈:2018-12-26
當在laravel 中編寫 api 介面時,throw new Exception() 返回的錯誤訊息格式不是我們想要的格式
解決辦法:
在 App\Exceptions目錄下新建一個 ApiException類 繼承 Exception
namespace App\Exceptions;
class ApiException extends \Exception{
public function __construct($message="")
{
parent::__construct($message);
}
}
之後,laravel 的所有錯誤處理都是在 App\Exceptions\Handler.php中處理的
這個類中主要有兩個方法 一個是 report 一個是render
report與我的的錯誤處理無關,我們在這裡要改寫一個 render方法
下面是render的原始方法
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { return parent::render($request, $exception); }
在render中我們可以判斷一下 $exception 是不是我們定義的 ApiException的一個例項,然後做相應的處理
程式碼如下
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { //如果$exception 是 ApiException的一個例項,則自定義返回的錯誤資訊 if($exception instanceof ApiException){ $result = [ "code"=>422, "msg"=>$exception->getMessage(), "data"=>"" ]; return response()->json($result); } //如果不是,則使用 父類的處理方法 return parent::render($request, $exception); }
此時,當在寫 api介面的時候,如果想丟擲一個錯誤,就可以使用 throw new ApiException("這是一個錯誤");
資料就會以 json格式返回錯誤資訊