【问题标题】:Catching exceptions in web api - Should I use a try-catch statement?在 web api 中捕获异常 - 我应该使用 try-catch 语句吗?
【发布时间】:2014-08-07 13:03:21
【问题描述】:

这是一个示例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);
        }
    }

在调试时,我得到了这个错误:

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,但问题是我应该使用try-catch 还是只保留上面的代码?)

【问题讨论】:

  • Based on the answer below 和 http://stackoverflow.com/questions/58380/avoiding-first-chance-exception-messages-when-the-exception-is-safely-handled,这是正常行为。
  • 除此之外,我还提到了http://stackoverflow.com/questions/12519561/asp-net-web-api-throw-httpresponseexception-or-return-request-createerrorrespon,以便更深入地了解。

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


【解决方案1】:

在 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());

【讨论】:

  • 谢谢。但我认为问题是不同的。我在问how to throw exceptions。我已经实现了custom exception、a exception filter attribute。问题是,is it just enough to use a throw statement 抛出异常? (我之所以这样问,是因为我收到了屏幕截图中的错误“the exception is not handled in the user-code”)
  • 你不必使用 try/catch
  • 那么,调试过程中出现的错误可以吗?我可以跳过那个错误。正确吗?
  • 是的,按 F5,你的处理程序会处理它。它被称为第一次机会异常,是一种调试功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2011-09-08
  • 2023-03-10
相关资源
最近更新 更多