其实对于C#异常处理你们都不陌生,可是对于在WeiApi上的异常处理实际上也和传统异常处理区别不大,可是却通过封装可让异常更加友好,https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling,经过微软的官方介绍,咱们能够知道WeiApi能够简单概述为三种异常,接下来咱们围绕这三种异常给出例子,如何封装和处理以上三种异常html
异常过滤器实现了System.Web.Http.Filters.IExceptionFilter接口。编写异常过滤器最简单的方法是从System.Web.Http.Filters.ExceptionFilterAttribute类派生并重写OnException方法。Microsoft给出的关于异常过滤器解释,那么如何实现呢?经过阅读《Asp.NET WEB API2 框架揭秘》,咱们知道每一次客户端请求API都会经过HTTP请求,服务端获得结果输出response到客户端。这个过程当中,一旦服务端发生异常,会统一贯客户端返回500的错误。web
那么在Web API中如何定义NotImplementedException类?首先在App_Start里面新建一个类WebApiExceptionFilterAttribute.cs,继承ExceptionFilterAttribute,重写OnException方法,代码以下api
1 public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute 2 { 3 //重写基类的异常处理方法 4 public override void OnException(HttpActionExecutedContext actionExecutedContext) 5 { 6 //1.异常日志记录(正式项目里面通常是用log4net记录异常日志) 7 Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "——" + 8 actionExecutedContext.Exception.GetType().ToString() + ":" + actionExecutedContext.Exception.Message + "——堆栈信息:" + 9 actionExecutedContext.Exception.StackTrace); 10 11 //2.返回调用方具体的异常信息 12 if (actionExecutedContext.Exception is NotImplementedException) 13 { 14 actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 15 } 16 else if (actionExecutedContext.Exception is TimeoutException) 17 { 18 actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.RequestTimeout); 19 } 20 //.....这里能够根据项目须要返回到客户端特定的状态码。若是找不到相应的异常,统一返回服务端错误500 21 else 22 { 23 actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError); 24 } 25 26 base.OnException(actionExecutedContext); 27 } 28 }
代码解析:经过判断异常的具体类型,向客户端返回不一样的http状态码,示例里面写了两个,能够根据项目的实际状况加一些特定的咱们想要捕获的异常,而后将对应的状态码写入http请求的response里面,对于一些咱们没法判断类型的异常,统一返回服务端错误500。Microsoft也有一个代码实现,可是没有封装服务器
要将过滤器应用于特定操做,请将过滤器做为属性添加到操做中:ide
public class ProductsController : ApiController { [NotImplExceptionFilter] public Contact GetContact(int id) { throw new NotImplementedException("This method is not implemented"); } }
要将过滤器应用于控制器上的全部操做,请将过滤器做为属性添加到控制器类中:post
[NotImplExceptionFilter] public class ProductsController : ApiController { // ... }
要将过滤器全局应用于全部Web API控制器,请将过滤器实例添加到GlobalConfiguration.Configuration.Filters集合中。此集合中的执行筛选器适用于任何Web API控制器操做。ui
GlobalConfiguration.Configuration.Filters.Add( new ProductStore.NotImplExceptionFilterAttribute());
若是须要,甚至能够向Status Code里面写入自定义的描述信息,而且还能够向咱们的Response的Content里面写入咱们想要的信息。咱们稍微改下OnException方法:this
if (actionExecutedContext.Exception is NotImplementedException) { var oResponse = new HttpResponseMessage(HttpStatusCode.NotImplemented); oResponse.Content = new StringContent("方法不被支持"); oResponse.ReasonPhrase = "This Func is Not Supported"; actionExecutedContext.Response = oResponse; }
异常过滤器是针对接口控制器以及全局定义,通常返回的都是服务器级别的错误,可是有的时候咱们须要定义业务异常的代码,那么若是是业务异常的状况下咱们就可使用HttpResponseException自定义异常,以下述代码:url
public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("没有找到产品ID = {0}的产品", id)), ReasonPhrase = "Product ID Not Found" } throw new HttpResponseException(resp); } return item; }
能够看到具体的业务异常信息是经过HttpResponseMessage封装,最后由HttpResponseException抛出,Microsoft没有解释HttpResponseMessage是什么,起初笔者觉得这是一个HttpResponseException的子类,可是跟踪了后发现HttpResponseMessage 继承了IDisposable接口,而IDisposable接口的主要用途是释放非托管的资源。 垃圾回收器自动释放再也不使用该对象时分配给托管对象的内存。 可是,不可能预测将发生垃圾回收。 此外,垃圾回收器具备不知道如窗口句柄的非托管资源,或打开文件和流。从描述上来看使用HttpResponseMessage时就表明发生了异常而且进行一次资源管理的回收,因此笔者认为,使用HttpResponseMessage能够更清晰的描述业务中所发生的 异常,而且在返回异常的时候进行一次垃圾回收,减小程序资源浪费
HttpError对象提供了一个一致的方式在回应主体中返回的错误信息。如下示例显示如何在响应正文中使用HttpError返回HTTP状态码404(Not Found)。经过Microsoft的解释就能够知道HttpError提供的是状态码返回,那么实际应用上更多的是将其和HttpResponseException一块儿使用。
public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { var message = string.Format("Product with id = {0} not found", id); throw new HttpResponseException( Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); } else { return item; } }
借鉴(Microsoft官网)ASP.NET Web API中的异常处理
在通常的项目中,能够定义好一些全体的关于服务器端的异常处理,而且封装好一个HttpResponseException自定义异常的处理,无需捕获HttpResponseException异常,Api会本身处理这个异常的,而且最好为每一个异常给出更加详细的HTTP状态码,可让异常更加精细友好