繁体   English   中英

异常处理和异步异常处理之间的区别

[英]Diference betwen Exception Handling and Async Exception handling

我创建了一个Web API应用程序,但不了解我的全局异常处理的工作方式。 以下代码不起作用:

public void Handle(ExceptionHandlerContext context){
    if (context.Exception is ObjectNotFoundException)
    {
        var result = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(context.Exception.Message),
            ReasonPhrase = "Nothing here for you"
        };

        context.Result = new ObjectNotFoundException(context.Request, result);
    }
}

但这很好用:

 public override void Handle(ExceptionHandlerContext context){
    if (context.Exception is ObjectNotFoundException)
    {
        var result = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(context.Exception.Message),
            ReasonPhrase = "Nothing here for you"
        };

        context.Result = new ObjectNotFoundException(context.Request, result);
    }
}

在您的代码中,唯一的区别是override关键字。 因此,这就是问题所在。

由于需要从基本抽象类ExceptionHandler覆盖Handles方法,因此您需要使用override关键字。

没有覆盖,您将创建一个新的实现并从中删除基本实现。 因此,方法调用从管道中删除,并且等效于那里没有此类方法。

如果你想要做的异步处理,你需要使用的,而不是“处理”,“HandleAsync”方法.. https://msdn.microsoft.com/en-us/library/system.web.http.exceptionhandling.exceptionhandler.handleasync (v = vs.118).aspx

任何异步处理程序都将启用非阻塞执行。 因此,如果您的日志记录/处理时间很长,或者由于管道中的请求过多而导致预期的负载,请使用异步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM