異常處理
1. 前言
本小節主要介紹如何處理異常錯誤情況,正確處理異??梢宰尳涌诟佑押茫绯霈F報錯,通常會出現 500
錯誤,異常處理之后可以返回 200
,錯誤內容只需在返回數據中體現。如返回數據中定義 code
字段,然后 code
字段不同的值就是告訴接口使用者發生了什么類型的錯誤,比如 code=401
表示權限不足,code=500
表示后端代碼層面內部錯誤,這樣就可以更友好的提示用戶使用。
2. 定義路由
下面給出異常捕獲測試的路由定義如下:
//異常捕獲測試
Route::get('exception-test','app\controller\Study\ExceptionController@testException');
如下圖所示:
3. 定義路由指定的控制器和方法
在 app\controller\Study
中新建 ExceptionController
控制器和 testException
方法:
<?php
namespace app\controller\Study;
use app\BaseController;
use app\Service\StudentService;
use think\facade\Log;
class ExceptionController extends BaseController
{
public function testException()
{
try{
$studentService = new StudentService();
$studentService->update();
}catch(\Exception $exception){
Log::write($exception->getMessage(),'test');
return json("內部錯誤:".$exception->getMessage());
}
return json("請求成功");
}
}
如下圖所示:
其中 StudentService
類的定義代碼如下:
<?php
namespace app\Service;
use app\Models\Study\StudentModel;
use think\Exception;
class StudentService
{
public function update($id = 1){
try {
$student = StudentModel::where('id',$id)->find();
//這里修改主鍵 id 的值,并保存會報錯
$student->id = "test";
$student->save();
}catch(\Exception $e){
throw new Exception("數據保存失敗:".$e->getMessage());
}
}
}
Tips: 上述代碼是為了演示方便故意寫的一個報錯代碼,目的是為了異常捕獲。
4. 請求接口
在 postman
中請求接口,返回數據如下:
Tips: 如圖所示可以使用異常捕獲之后,可以防止由于代碼邏輯錯誤導致的內部
500
,從而返回友好的200
,上述展示的是多層異常捕獲。
5. 主動拋出異常
上述 StudentService
類中 update
方法也可以定義如下方式主動拋出異常:
public function update($id = 0){
if(!$id){
throw new Exception("id必須大于0");
}
$student = StudentModel::where('id',$id)->find();
if(empty($student)){
throw new Exception("學生信息不存在");
}
}
如下圖所示:
此時再調用接口返回如下圖:
6. 小結
本小節介紹了如何使用異常捕獲,異常捕獲可以有效地捕捉多層調用關系的內部異常,當內部代碼出現報錯情況時,在控制器入口處捕獲異??梢杂行У刈柚?500
錯誤碼,然后返回更加友好的 200
狀態碼。
Tips: 代碼倉庫:https://gitee.com/love-for-poetry/tp6