[英]Whats the correct HTTP status code answer for specific Exceptions
我正在使用MVC 5的ASP.NET Web API在C#中創建REST Web API。
我創建了一個抽象類BaseApiController
,所有API控制器都對其進行了擴展。 在此基本控制器中,我處理所有異常以及控制器正常工作所需的一切。
我已經為以下異常實現了異常處理:
public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
{
string controllerName = null;
string actionName = null;
try
{
SetContext(controllerContext);
SetServices();
await AuthenticateUser();
controllerName = controllerContext?.Controller?.GetType().FullName;
var services = controllerContext?.ControllerDescriptor?.Configuration?.Services;
actionName = services?.GetActionSelector()?.SelectAction(controllerContext)?.ActionName;
return await base.ExecuteAsync(controllerContext, cancellationToken);
}
catch (HttpResponseException e)
{
ClientDataService.Logger(e, $"{controllerName}.{actionName}",
$"Response -> Status Code: {(int)e.Response.StatusCode}, Reason: {e.Response.ReasonPhrase}",
SystemLogOriginTypesEnum.WEBSITE_API);
throw;
}
catch (Exception e)
{
ClientDataService.Logger(e, $"{controllerName}.{actionName}",
$"Response -> Status Code: {(int)HttpStatusCode.InternalServerError}, Reason: Internal server error",
SystemLogOriginTypesEnum.WEBSITE_API);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Internal server error"),
ReasonPhrase = "Internal server error"
});
}
控制器主要在未傳遞強制性參數或未正確設置強制性參數(HTTP狀態代碼400)時引發HttpResponseException
,第二個錯誤是在發生嚴重錯誤(HTTP狀態代碼500)時。
我的問題是,當服務引發諸如NotSupportedException
或自定義InvalidSortAttributeException
類的異常時,API應該響應哪種HTTP狀態代碼?
我不是說HTTP狀態類別,即4XX與5XX,因為InvalidSortAttributeException
應該是4XX類別,因為錯誤是從無效請求(可能是400(錯誤請求))拋出的!
盡管第二種,但我認為可能會屬於這兩種類別,因為服務器不支持該請求,但這並不完全意味着將來將不支持該請求,可能是406(不可接受)或501(未實現)?
4XX專為用戶錯誤而構建5XX專為內部服務器錯誤而構建
您必須使用針對該場景的智能代碼進行響應。 如果存在一個不受支持的異常,但是您的代碼調用者構造了一個不受支持的方案,則為500。如果用戶設法將一個錯誤的請求放在一起,則應為4XX。
還要注意,在JSON請求中缺少屬性(400)與在URL中缺少值(404)或資源不再可用(404)之間存在差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.