WebApi2官网学习记录---异常处理
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
- 在action上
- 在Controller上
- 在全局
方式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官网学习记录---异常处理的更多相关文章
- WebApi2官网学习记录---Cookie
Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...
- WebApi2官网学习记录---批量处理HTTP Message
原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...
- WebApi2官网学习记录---Html Form Data
HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...
- WebApi2官网学习记录--HttpClient Message Handlers
在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...
- WebApi2官网学习记录--HTTP Message Handlers
Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...
- WebApi2官网学习记录---Configuring
Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...
- WebApi2官网学习记录--- Authentication与Authorization
Authentication(认证) WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...
- WebApi2官网学习记录---单元测试
如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...
- WebApi2官网学习记录---Tracing
安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...
随机推荐
- 填坑 - 使用Entity Framework 6 + Sqlite进行DB first开发
Sqlite团队也是渣啊,到第6代了还不支持Code First. 1.安装运行环境和组件 .安装SQLite的Visual Studio设计器支持 只有安装了它,在[新建ADO.NET实体数据模型] ...
- IPointCollection,ISegmentCollection和IGeometryCollection
Engine 提供了三个主要的几何图形集合接口用于对几何对象的操作,分别是 IPointCollection,ISegmentCollection 和 IGeometryCollection,这些接口 ...
- vsftpd安装、多用户配置
1.vsftpd安装 rpm -ivh vsftpd 2.2.2 11.el6_4.1.x86_x64.rpm 2.添加ftp用户 添加ftp用户组 groupadd ftpg 添加ftp用户 use ...
- unity中数据的持久化存储
unity 提供了PlayerPrefs这个类用于存储游戏数据到电脑硬盘中. 这个类有10个函数可以使用 Class Functions类函数 SetInt Sets the value of the ...
- MySQL 使用索引扫描来做排序
MySQL有两种方式可以生成有序的结果:通过排序操作:或者按照索引顺序扫描:如果EXPLAIN 出来的结果的type列的值为“index”,则说明MySQL使用了索引扫描来做排序(不要和Extra列的 ...
- 后台构建 html 字符串传到前台字符串转码(html)处理
知识在于总结,那就记下了吧! 例如后台 html 字符串是 var htmlStr="后台html字符串": 转码 var html格式代码=decodeHtml(htmlStr) ...
- .attr()和.prop()和.css()的区别
是不是新手都会遇到这个问题?遇到过一次,在网上搜一搜,综合成了下面这样.重点参考了dolphin的‘jQuery的attr与prop’, 写的很清楚呢. 一般attribute翻译成中文术语为“特性” ...
- [Mugeda HTML5技术教程之4] Studio 概述
Mugeda Studio 是基于云平台的制作HTML5动画的专业可视化集成开发环境,可以让你在不需要安装客户端程序的情况下,只通过浏览器就能轻松创作高质量的HTML5动画.HTML5动画相对于传统的 ...
- 面试题:获取大量数据中某一条的index
提问: 群里分享了一个面试题:页面里有很多条数据,怎么知道这条数据的index,并且不使用循环? 分析: 如果在数组里,直接用indexOf,但对于对象会比较麻烦. 在页面上,不使用循环的话,可以用定 ...
- Jasper_crosstab_display a value of field in crosstab total row
1.create a measure <measure name="myField" class="java.lang.String"> <m ...