特定异常的正确HTTP状态代码答案是什么

时间:2019-03-31 15:35:37

标签: c# asp.net-web-api

我正在使用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状态代码)的情况下,控制器抛出HttpResponseException  400),第二个是发生了严重错误(HTTP状态码500)。

我的问题是,当服务引发NotSupportedException或自定义InvalidSortAttributeException之类的异常时,API应该响应哪种HTTP状态代码?

我不是说HTTP状态类别,即4XX与5XX,因为InvalidSortAttributeException应该是4XX类别,因为错误是从无效请求(可能是400(错误请求))抛出的!?< / p>

尽管第二种,但我认为可能会属于这两种类别,因为服务器不支持该请求,但这并不表示将来将不支持该请求,可能是406(不可接受)或501(未实现) )?

1 个答案:

答案 0 :(得分:0)

4XX专为用户错误而构建 5XX专为内部服务器错误而构建

您必须使用针对该场景的智能代码进行响应。如果存在不受支持的异常,但您的代码调用者构造了不受支持的方案,则为500。如果用户设法将错误的请求组合在一起,则应为4XX。

还要注意,在JSON请求中缺少属性(400)与在url中缺少值(404)或资源不再可用(404)之间是有区别的。