HttpResponseException

当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误。

HttpResonseException是一个特别的情况,这个异常可以返回任意指定的http status code,也可以返回具体的错误信息。

 public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
} public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
}
throw new HttpResponseException(resp);
}
return item;
}

Exception Filters

可以自定义一个exception filter处理异常信息,当一个Controller中的方法抛出未捕获的异常(不包括HttpResponseException)filter会被执行。

Exception filters实现System.Web.Http.Filters.IExceptionFilter接口,最简单的方式是实现 System.Web.Http.Filters.ExceptionFilterAttribute类来进行自定义的exception filter

注册自定义的Exception Filters

  1. 在action上
  2. 在Controller上
  3. 在全局
 方式1:
public class ProductsController : ApiController
{
[NotImplExceptionFilter]
public Contact GetContact(int id)
{
throw new NotImplementedException("This method is not implemented");
}
} 方式2:
[NotImplExceptionFilter]
public class ProductsController : ApiController
{
// ...
} 方式3:
GlobalConfiguration.Configuration.Filters.Add(
new ProductStore.NotImplExceptionFilterAttribute());

HttpError

HttpError对象提供了一个统一的返回错误信息的方式

 public HttpResponseMessage GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, item);
}
}

在内部CreateErrorResponse创建了一个HttpError的实例,然后创建一个包含HttpError的HttpResponseMessage。返回的错误消息的格式与content-negotiation选择的formatter有关。

 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;
}
} public HttpResponseMessage PostProduct(Product item)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
} // Implementation not shown...
}

WebApi2官网学习记录---异常处理的更多相关文章

  1. WebApi2官网学习记录---Cookie

    Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...

  2. WebApi2官网学习记录---批量处理HTTP Message

    原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...

  3. WebApi2官网学习记录---Html Form Data

    HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...

  4. WebApi2官网学习记录--HttpClient Message Handlers

    在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...

  5. WebApi2官网学习记录--HTTP Message Handlers

    Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...

  6. WebApi2官网学习记录---Configuring

    Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...

  7. WebApi2官网学习记录--- Authentication与Authorization

    Authentication(认证)   WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...

  8. WebApi2官网学习记录---单元测试

    如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...

  9. WebApi2官网学习记录---Tracing

    安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...

随机推荐

  1. Android(性能)

    ■ 数据传输 对象和字节流之间的转换 为什么要转? 持久化(装逼说法,JVM非运行的场合),他进程(装逼说法,其他机器JVM,不同的JVM) Parcelable和Serializable 初衷: P ...

  2. arcmap从excel坐标数据生成点shp文件

    概述 今天试图在ArcMap中将excel数据转成点文件,在"Display XY Data"的时候,无法选择X,Y字段,很是纳闷,原来Excel中列的格式是文本,导致无法选择.有 ...

  3. iOS基础框架的搭建 / 及国际化操作

    1.基础框架的搭建 1.1 pod引入常用的第三方类库 1.2 创建基础文件夹结构/目录结构 Resource———存放声音/图片/xib/storyboard 等资源文件 Define——宏定义, ...

  4. Carthage使用(cocoapods的替代)

    1.使用homebrew安装Carthage brew intsall carthage  Ps:没有安装Homebrew的话,进入传送门Homebrew.顺便提一句可以选择简体中文啊.   2.进入 ...

  5. struct可以拥有class般的构造函数

    struct A { int a, b; A(int x, int y) :a(x), b(y){} }; int main() { A a(1, 2); cout << a.a < ...

  6. POJ1995 Raising Modulo Numbers(快速幂)

    POJ1995 Raising Modulo Numbers 计算(A1B1+A2B2+ ... +AHBH)mod M. 快速幂,套模板 /* * Created: 2016年03月30日 23时0 ...

  7. Go语言之defer

    defer语句被用于预定对一个函数的调用.我们把这类被defer语句调用的函数称为延迟函数.注意,defer语句只能出现在函数或方法的内部. 一条defer语句总是以关键字defer开始.在defer ...

  8. java学习笔记 (8) —— Struts2 实现上传

    1.新建upload.jsp <%@ page language="java" import="java.util.*" pageEncoding=&qu ...

  9. windows下配置lamp环境(4)---安装MySQL数据库5.6

    图解安装MySQL数据库 1.获取软件就多不说了 2.双击开始安装 3.点击点击NEXT进行下一步 4.同意协议,点击NEXT进入下一步 5.选择指定安装位置安装方法,进入安装位值选择页面: 6.分别 ...

  10. How many ways??(HDU 2157)

    How many ways?? Sample Input 4 4 //n个点,m条路径0 1 //s->t可通0 21 32 32 //询问数0 3 2 //从0到3走两条路可到的方案有多少种0 ...