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();
} return HandleAsyncCore(context, cancellationToken);
} public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
HandleCore(context);
return Task.FromResult();
} 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();
}

ErrorHandling in asp.net web api的更多相关文章

  1. Exception Handling in ASP.NET Web API webapi异常处理

    原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...

  2. Global Error Handling in ASP.NET Web API 2(webapi2 中的全局异常处理)

    目前,在Web API中没有简单的方法来记录或处理全局异常(webapi1中).一些未处理的异常可以通过exception filters进行处理,但是有许多情况exception filters无法 ...

  3. 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

    由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...

  4. ASP.NET Web API Model-ActionBinding

    ASP.NET Web API Model-ActionBinding 前言 前面的几个篇幅把Model部分的知识点划分成一个个的模块来讲解,而在控制器执行过程中分为好多个过程,对于控制器执行过程(一 ...

  5. ASP.NET Web API Model-ParameterBinding

    ASP.NET Web API Model-ParameterBinding 前言 通过上个篇幅的学习了解Model绑定的基础知识,然而在ASP.NET Web API中Model绑定功能模块并不是被 ...

  6. ASP.NET Web API Model-ModelBinder

    ASP.NET Web API Model-ModelBinder 前言 本篇中会为大家介绍在ASP.NET Web API中ModelBinder的绑定原理以及涉及到的一些对象模型,还有简单的Mod ...

  7. ASP.NET Web API Model-ValueProvider

    ASP.NET Web API Model-ValueProvider 前言 前面一篇讲解了Model元数据,Model元数据是在Model绑定中很重要的一部分,只是Model绑定中涉及的知识点比较多 ...

  8. ASP.NET Web API Model-ModelMetadata

    ASP.NET Web API Model-ModelMetadata 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...

  9. ASP.NET Web API 过滤器创建、执行过程(二)

    ASP.NET Web API 过滤器创建.执行过程(二) 前言 前面一篇中讲解了过滤器执行之前的创建,通过实现IFilterProvider注册到当前的HttpConfiguration里的服务容器 ...

随机推荐

  1. delphi xe-system.json

    Delphi XE10有一个对JSON处理的单元,在你需要使用JSON的单元里面引入"System.json",随后你就可以用Delphi自己的json处理类了. 普通解析 实例1 ...

  2. delphi------项目类型

    Console Application:控制台应用程序 writeln('HelloWorld'); //接收用户输入字符 readln: //直到用户输入回车结束 VCL Forms Applica ...

  3. delphi 事件记录

    delphi常用事件 序号 事件 描述 1. OnActive 焦点称到窗体或控件时发生 2. OnClick 鼠标单击事件 3. OnDbClick 鼠标双击事件 4. OnClose和OnClos ...

  4. 帝国CMS 7.2数据导入后的参数修正

    1.日期转时间戮,HTML文件名,目录名更改 update cms_ecms_jdba set newstime = UNIX_TIMESTAMP(submitTime),titleurl = CON ...

  5. sublime使用及插件

    转自 http://www.cnblogs.com/Rising/p/3741116.html

  6. FW: Nginx模块开发入门

    前言 Nginx是当前最流行的HTTP Server之一,根据W3Techs的统计,目前世界排名(根据Alexa)前100万的网站中,Nginx的占有率为6.8%.与Apache相比,Nginx在高并 ...

  7. php5.4 的 php-fpm 的重启

    php 5.3.3以后 源码中已经内嵌了 php-fpm,不用象以前的php版本一样专门打补丁了,只需要在configure的时候添加编译参数即可. 关于php-fpm的编译参数有 –enable-f ...

  8. RTSP客户端接收存储数据(live555库中的openRTSP实例)

    一.openRTSP编译运行 a)windows下编译运行 还是以mediaServer作为服务端,openRTSP作为客户端 b)Linux下编译运行 转自http://kuafu80.blog.1 ...

  9. python2函数

    1.函数的定义 函数的定义形式如下: def <name>(arg1,arg2...argN): <statements> 函数的名字必须以字母开头,可以包括下划线.函数的目的 ...

  10. Grunt JS构建环境搭建以及使用入门

    Grunt JS构建环境搭建以及使用入门 1.应用场景 一种自动化任务处理工具,对于日常的需求(代码规则检查.代码合并)可以实现自动化执行,只需要保留package.json和Gruntfile.js ...