捕获web api中的异常 - 我应该使用try-catch语句吗?

时间:2014-06-17 13:28:31

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

这是使用<{1}}的示例

ApiController

这是我的[RequestExceptionFilter] public class RequestController : ApiController { public IHttpActionResult Post([FromBody]Request RequestDTO) { //some code over here throw new DTONullException(typeof(Request.Models.DTO.Request));

custom exception handler

在调试时,我收到此错误:

public class RequestExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is DTONullException) { context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("DTO is null"), ReasonPhrase = "DTO is null", }; } base.OnException(context); } }

enter image description here

我应该在这里使用An exception of type 'Request.Controllers.DTONullException' occurred in Request.dll but was not handled in user code语法吗?惯例是什么?

在我在互联网上看到的所有样本中,人们只是try-catch,但他们似乎没有抓住它。

(当然,如果我按throw the exception,应用程序会按预期返回Run,但问题是我应该使用BadRequest还是只保留上面的代码?)

1 个答案:

答案 0 :(得分:3)

在ASP.NET中捕获异常的唯一可靠方法(无论您使用的是WebForms / MVC / WebApi)是global.asax中的Application_Error事件。

然而,您演示的例外情况可能会被IExceptionHandler抓住。

class OopsExceptionHandler : ExceptionHandler
{
    public override void HandleCore(ExceptionHandlerContext context)
    {
        context.Result = new TextPlainErrorResult
        {
            Request = context.ExceptionContext.Request,
            Content = "Oops! Sorry! Something went wrong." +
                      "Please contact support@contoso.com so we can try to fix it."
        };
    }

    private class TextPlainErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = 
                             new HttpResponseMessage(HttpStatusCode.InternalServerError);
            response.Content = new StringContent(Content);
            response.RequestMessage = Request;
            return Task.FromResult(response);
        }
    }
}

并在您的webapi2配置中添加以下内容:

config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());