ErrorHandling in asp.net web api

https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling

https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling

Solution Overview

We provide two new user-replaceable services, IExceptionLogger and IExceptionHandler, to log and handle unhandled exceptions. The services are very similar, with two main differences:

  1. We support registering multiple exception loggers but only a single exception handler.
  2. Exception loggers always get called, even if we're about to abort the connection. Exception handlers only get called when we're still able to choose which response message to send.

Both services provide access to an exception context containing relevant information from the point where the exception was detected, particularly the HttpRequestMessage, the HttpRequestContext, the thrown exception and the exception source (details below).

 

When to Use

  • Exception loggers are the solution to seeing all unhandled exception caught by Web API.
  • Exception handlers are the solution for customizing all possible responses to unhandled exceptions caught by Web API.
  • Exception filters are the easiest solution for processing the subset unhandled exceptions related to a specific action or controller.

 

复制代码
 public class ExceptionHandler : IExceptionHandler
    {
        public virtual Task HandleAsync(ExceptionHandlerContext context,
            CancellationToken cancellationToken)
        {
            if (!ShouldHandle(context))
            {
                return Task.FromResult(0);
            }

            return HandleAsyncCore(context, cancellationToken);
        }

        public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
            CancellationToken cancellationToken)
        {
            HandleCore(context);
            return Task.FromResult(0);
        }

        public virtual void HandleCore(ExceptionHandlerContext context)
        {
        }

        public virtual bool ShouldHandle(ExceptionHandlerContext context)
        {
            return context.ExceptionContext.CatchBlock.IsTopLevel;
        }
    }
复制代码

 

 

 

https://stackoverflow.com/questions/22038800/can-anyone-explain-the-work-flow-of-iexceptionhandler-with-sample-client-applica

CatchBlock.IsTopLevel

IsOutermostCatchBlock does not exists. Use CatchBlock.IsTopLevel instead:

public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
  return context.ExceptionContext.CatchBlock.IsTopLevel;
}

Source on NuDoq: ExceptionHandlerContext and ExceptionContextCatchBlock

 

https://stackoverflow.com/questions/21901808/need-a-complete-sample-to-handle-unhandled-exceptions-using-exceptionhandler-i

You don't need to implement IExceptionHandler low level mechanism yourself.

Instead, you can simply inherit from ExceptionHandler and override the Handle method.

public class MyExceptionHandler : ExceptionHandler
{
  public override void Handle(ExceptionHandlerContext context)
  {
    //TODO: Do what you need to do
    base.Handle(context);
  }
}

ExceptionHandler implements IExceptionHandler and manage basic core mechanisms (like async and that exception should be handled or not).

Use your exception handler like that:

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

 

ActionFilter中的异常不会被捕获,但是会被外部的api调用知道

复制代码
 public class ValidateModelAttribute : ActionFilterAttribute

{

public override async void OnActionExecuting(HttpActionContext actionContext)
{

        //throw an exception  here 

}

}
复制代码

这是因为底层的调用中,进行了try catch,所以这个异常是不会被捕获的。

这样做的好处是,action filter出错,不会影响其他的action filter. 并且最终还是会去调用api。只是最后会检查到Error

https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Web.Http/Filters/ActionFilterAttribute.cs

复制代码
 public virtual Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            try
            {
                OnActionExecuting(actionContext);
            }
            catch (Exception ex)
            {
                return TaskHelpers.FromError(ex);
            }

            return TaskHelpers.Completed();
        }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(298)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-01-22 sqlserver资源下载
点击右上角即可分享
微信分享提示