[英]How implement error in Rest API?
我想知道哪種是在RestAPI中實現錯誤的方法,實際上,如果類中的方法生成異常,我將返回此錯誤...
if(mysqli_connect_errno()) {
throw new Exception("Can't connect to db.");
}
...但這是一個不好的做法,因為API應該返回json。
所以我的想法是創建一個名為Errors
的類,在每個類中,當引發錯誤時,我只需調用相對錯誤號即可顯示json錯誤。
有人有其他想法嗎?
也許像這樣:
<?php
try {
// Do your stuff
if(mysqli_connect_errno()) {
throw new Exception("Can't connect to db.");
}
} catch (Exception $e) {
echo json_encode(array("success" => false, "message" => $e->getMessage()));
return;
}
我認為您的做法正確。 您在這里要處理幾個問題。 第一個是錯誤處理,第二個是錯誤格式化。
錯誤處理可以通過多種方式完成,引發異常是其中之一。 為了找出什么時候發生了不好的事情,您需要將異常包裝在try / catch塊中:
try {
//logic
if(mysqli_connect_errno()) {
throw new Exception("Can't connect to db.");
}
//more logic
} catch (Exception $e) {
//handle the error here
}
如果您遵循此路線,建議您對例外情況進行更詳細的說明,以便更好地在API中構建響應。 例如,關閉數據庫與無法找到資源並不相同,例如:
try {
//logic
if(mysqli_connect_errno()) {
throw new DBException("Can't connect to db.");
}
if(is_null($entity)) {
throw new ResourceNotFoundException("Entity could not be found");
}
//more logic
} catch (DBException $e) {
//handle DB error here
} catch (ResourceNotFoundException $e) {
//handle resource not found error here
}
現在,對於格式化部分 ,REST API中的常規響應是JSON響應。 一種解決方法是創建一個特定的類,其唯一職責是將您的響應轉換為有效的JSON:
...
} catch (DBException $e) {
return $this->JSONResponse->format("Sorry we could not complete your request", 500);
} catch (ResourceNotFoundException $e) {
return $this->JSONResponse->format("The resource you were looking for could not be found", 404);
}
如您所見,不同的錯誤具有不同的狀態代碼。 該類的實現很簡單:
class JSONResponse {
public function format($message, $statusCode) {
return json_encode(['message' => $message, 'code' => $statusCode]);
}
}
但是,這不會更改響應的狀態碼,這對於良好的REST API設計至關重要。 您需要使用此功能設置適當的狀態代碼。
您可以在Symfony HTTPFoundation組件中找到該類的更健壯和靈活的實現,該組件是從正常Response類擴展的。
我認為@Gwendal答案很好,但僅返回json響應還不夠,還必須返回正確的http代碼:
<?php
try {
// Do your stuff
} catch (Exception $e) {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo json_encode(array("success" => false, "message" => $e->getMessage()));
return;
}
我的RESTful API始終返回以下結構的JSON:
[
'resource' : [],
'code' : [
'id' : int,
'msg' : string
],
'meta' : [],
'log' : []
]
如果我返回數據,則數據始終在resource
並且code['id']
始終為0(表示“確定”)。 當發生錯誤時,我返回一個空resource
和一些錯誤code
。 我還通過meta
提供了一些額外的信息,並且可以通過log
記錄一些操作,這對調試很有幫助。
這也可能會幫助您解決將來的問題,例如,如果您想將答案分成多個頁面,以便客戶端應通過GET /path/to/resource/page/:page
請求數據,或希望通知客戶端某個請求路徑不推薦使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.