異常處理
1. 前言
本小節(jié)主要介紹如何處理異常錯誤情況,正確處理異常可以讓接口更加友好,如出現(xiàn)報錯,通常會出現(xiàn) 500
錯誤,異常處理之后可以返回 200
,錯誤內(nèi)容只需在返回數(shù)據(jù)中體現(xiàn)。如返回數(shù)據(jù)中定義 code
字段,然后 code
字段不同的值就是告訴接口使用者發(fā)生了什么類型的錯誤,比如 code=401
表示權限不足,code=500
表示后端代碼層面內(nèi)部錯誤,這樣就可以更友好的提示用戶使用。
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("內(nèi)部錯誤:".$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("數(shù)據(jù)保存失敗:".$e->getMessage());
}
}
}
Tips: 上述代碼是為了演示方便故意寫的一個報錯代碼,目的是為了異常捕獲。
4. 請求接口
在 postman
中請求接口,返回數(shù)據(jù)如下:
Tips: 如圖所示可以使用異常捕獲之后,可以防止由于代碼邏輯錯誤導致的內(nèi)部
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("學生信息不存在");
}
}
如下圖所示:
此時再調(diào)用接口返回如下圖:
6. 小結
本小節(jié)介紹了如何使用異常捕獲,異常捕獲可以有效地捕捉多層調(diào)用關系的內(nèi)部異常,當內(nèi)部代碼出現(xiàn)報錯情況時,在控制器入口處捕獲異??梢杂行У刈柚?500
錯誤碼,然后返回更加友好的 200
狀態(tài)碼。
Tips: 代碼倉庫:https://gitee.com/love-for-poetry/tp6