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. JQuery中常用的 属性选择器

    jQuery中使用$()作为选择符极大提高工作效率以及方便快捷;一些常用属性的选择器由以下几种 1) $('#id') id选择器 2) $('.class') css选择器,class类名 3) $ ...

  2. WPF DataGrid 之数据绑定

    1. Auto generation of columns 最简单的方法莫过于让DataGrid根据数据源中的字段自动生成列了: 根据实体类的公共属性, 能够自动生成四种类型的数据列,对应关系如下: ...

  3. SQL流程控制语句学习(三):while break continue

    1.while语法 while   布尔表达式 {sql语句或语句块} break  --跳出本层循环 {sql语句或语句块} continue  --跳出本次循环 {sql语句或语句块} 2.whi ...

  4. Arcgis Engine - 鹰眼(减少闪烁)

    网上看到的代码,都是一个模样,经过不断调试,无意中效果就可以了.主要是在"鼠标拖动的时候",网上的代码的鹰眼效果,感觉坑爹死了,闪烁超级严重.主要原因是鼠标拖动的时候,进行时时更新 ...

  5. Linux最小化安装后配置网络

    vi /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0HWADDR=00:0C:29:DD:AD:B9TYPE=EthernetUUID=d7 ...

  6. java下tcp的socket连接

    serverDemo package cn.stat.p4.ipdemo; import java.io.IOException; import java.io.InputStream; import ...

  7. MySql中PreparedStatement对象与Statement对象

    PreparedStatement对象与Statement对象相比   1.代码的可读性和可维护性. 2.PreparedStatement能保证安全性(解决sql注入问题) 3.PreparedSt ...

  8. uva12489 Combating cancer(树同构)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud https://uva.onlinejudge.org/index.php?opt ...

  9. 利用System.Net.Mail和多线程实现邮件发送

    对于邮件发送,一般来说,程序会响应超过1秒,这样对于用户体验来说,让用户等待的时间过长,而且发送的邮件越多时间就越长,所以这里我利用了线程的来处理邮件发送这种耗时的工作,废话不多说,直接上代码 pri ...

  10. div弹出登录窗口

    <meta charset="utf-8"/> <script type="text/javascript"> //弹出式登录 func ...