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 WiFiDirect 学习(二)——Service Discovery

    Service Discovery 简介 在Android WifiDirect学习(一 )中,简单介绍了如何使用WifiDirect进行搜索——连接——传输. 这样会有一个问题,那就是你会搜索到到附 ...

  2. Linux 定时执行shell脚本_crontab

    1.查看任务[oracle@XXXXX OracleBackA]$ crontab -l 2.新增任务[oracle@XXXXX OracleBackA]$ crontab -e 3.每天14点40执 ...

  3. jQuery事件与事件对象

    事件是脚本编程的灵魂,本篇来介绍jQuery中的事件处理及事件对象. 事件与事件对象 首先,我们来看一下经常使用的添加事件的方式: <input type="button" ...

  4. [.NET]Repeater控件使用技巧

    1.控制Repeater表格中的按钮显隐 1.1 定义方法 public void Repeater1_ItemDataBinding(object sender, RepeaterItemEvent ...

  5. java学习笔记(3):java的工作原理及相关基础

    一.运行机制 如上图所示,图中内容即为Java的运行机制: 1.我们一开始所编写的代码文件存储格式为(如text.java)文件,这就是源程序文件 2.在Java编辑器的作用下,也就是就行了编译,形成 ...

  6. POJ 1151 - Atlantis 线段树+扫描线..

    离散化: 将所有的x轴坐标存在一个数组里..排序.当进入一条线段时..通过二分的方式确定其左右点对应的离散值... 扫描线..可以看成一根平行于x轴的直线..至y=0开始往上扫..直到扫出最后一条平行 ...

  7. Google Guava的splitter用法

    google的guava库是个很不错的工具库,这次来学习其spliiter的用法,它是一个专门用来 分隔字符串的工具类,其中有四种用法,分别来小结 1 基本用法: String str = " ...

  8. jQuery+Ajax+PHP+Mysql实现分页显示数据

    css <style type="text/css"> #loading{ position: absolute; top: 200px; left:400px; } ...

  9. 详解CSS设置默认字体样式

    浏览器默认的样式往往在不同的浏览器.不同的语言版本甚至不同的系统版本都有不同的设置,这就导致如 果直接利用默认样式的页面在各个浏览器下显示非常不一致,于是就有了类似YUI的reset之类用来尽量重写浏 ...

  10. 转载自php 大牛的学习计划 人生规划

    2012年偶决定开始写博客了,不为别的,就希望可以通过博客记录我的成长历程同时也希望可以帮助一些刚毕业,刚入行业的兄弟姐们们.我们是一群充满浮躁.抱怨.迷茫的程序猿,想一想3年就这么过去了,社会变得更 ...