1 app\exceptions 目錄下 新建 Apiexception.php
<?php namespace App\Exceptions; /*** * API 自定義異常類 */ use Exception; class ApiException extends Exception { //自定義異常處理 public function SetErrorMessage($errorMsg='', $errorCode = '500'){ $this->errorMsg = $errorMsg; $this->errorCode = $errorCode; return $this; } }
2 修改 app\exceptions\handler.php 文件
/** * 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) { // 如果config配置debug為true ==>debug模式的話讓laravel自行處理 $debug_status = config('app.debug'); // .env文件配置 if($debug_status){ return parent::render($request, $exception); } return $this->handle($request, $exception); } /** * 異常接管 * */ public function handle($request, Exception $exception){ //如果是接口請求,則拋出json if($request->is('api/*')) { // 只處理自定義的APIException異常 if($exception instanceof \APP\Exceptions\ApiException ) { //此處寫ApiException文件所處路徑 $result = [ "status" => 2 , //操作狀態: 1 成功 2 失敗 "errorCode"=>$exception->errorCode, "msg" => $exception->errorMsg, "result" => '', ]; return response()->json($result); } //此處可以寫多個自定義異常類 if($exception instanceof \APP\Exceptions\otherException ) { $result = [ "status" => 2 , //操作狀態: 1 成功 2 失敗 "errorCode"=>$exception->errorCode, "msg" => $exception->errorMsg, "result" => '', ]; return response()->json($result); } # 繼續寫其他自定義異常 /*** * code * * ***/ } return parent::render($request, $exception); }
3 使用
<?php namespace App\Http\Controllers\Test; use Illuminate\Routing\Controller; use App\Exceptions\ApiException; class IndexController extends Controller { public function index(){ throw (new ApiException)->SetErrorMessage("錯了",'500'); } }
這就ok了
整體思路: 使用時候,先實例 自定義 異常。把錯誤信息傳過去, 然后會回到 handler.php 里邊顯示
注意事項:
1 測試時候。要注冊一個路由在訪問
2 注意開啟debug 在.env 文件里邊
