一、HttpResponseException

  如果一个Web API控制器抛出一个未捕捉异常,默认地,大多数异常都会被转化成一个带有状态码“500 – 内部服务器错误”的HTTP响应。HttpResponseException(HTTP响应异常)类型会返回你在异常构造器中指定的任何HTTP状态码。例如,在以下方法中,如果id参数非法,会返回“404 — 未找到”。

public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
     //指定响应状态码
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}

  为了对响应进行更多控制,你也可以构造整个响应消息HttpResponseMessage,并用HttpResponseException来包含它:

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"
}
     //包含一个HttpResponseMessage
throw new HttpResponseException(resp);
}
return item;
}

二、Exception Filters

  继承ExceptionFilterAttribute,重写OnException,最后都是抛出HttpResponseException,包含一个HttpResponseMessage,调用客户端可以获取该异常信息,进行相应处理。

 public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception != null && !(context.Exception is HttpResponseException))
{
MetricsConfig.MarkException(context.Exception); if (context.Exception is UnauthorizedAccessException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
} var exceptionData = new ExceptionData
{
Name = context.Exception.GetType().Name,
Message = context.Exception.GetBaseException().Message
}; if (context.Exception is ApplicationException)
{
exceptionData.Message = context.Exception.Message;
var businessException = context.Exception as CustomBusinessException;
if (businessException != null)
{
exceptionData.Data = businessException.Data;
}
} throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new ObjectContent<ExceptionData>(exceptionData, JsonFormatter),
ReasonPhrase = context.Exception.GetType().Name
}); }
} private JsonMediaTypeFormatter _JsonFormatter;
private JsonMediaTypeFormatter JsonFormatter
{
get
{
if (_JsonFormatter == null)
{
_JsonFormatter = new JsonMediaTypeFormatter();
_JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
return _JsonFormatter;
}
} // A simple class for generate response with json content.
public class ExceptionData
{
public string Name { get; set; }
public string Message { get; set; }
public string Data { get; set; }
}
}

  注册:

  以下是全局注册,当然也可以在Controller或Action上标注

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{ // register exception handler.
config.Filters.Add(new ExceptionHandlingAttribute()); }
}

三、客户端获取异常

  通过AngularJs中AOP拦截响应实现

// apiInterceptor is responsible to handle the aspect of each request and response.
webservices.factory('apiInterceptor',
['$q', '$log', '$injector', 'loginContext', 'eventAggregator', function ($q, $log, $injector, loginContext, eventAggregator) {
'use strict'; var apiToken = loginContext.apiToken;
var tokenType = loginContext.tokenType;
var webApiHostUrl = loginContext.apiHost + "/api/v1"; return {
//token save to services for further usage
tokenType: tokenType,
apiToken: apiToken,
webApiHostUrl: webApiHostUrl, // On request success 请求拦截
request: function (config) {
if (config.isWebApiRequest && !config.isPlugin) {
          //地址上都自动附加上/api/v1
config.url = (config.mkApiUrl || webApiHostUrl) + config.url;
config.headers = config.headers || {};
          //添加Authorization,用tokeentype token格式来定义 ,如 ‘bearer sfsfsfsfsdf=sfsf+...’
config.headers.Authorization = tokenType + ' ' + (config.mkToken || apiToken);
var specificOfficeId = Ares.specificOfficeUtil.getOfficeId();
if (specificOfficeId) {
config.headers["specific-office-id"] = specificOfficeId;
}
} else if (config.handleApiRequest) {
config = config.handleApiRequest(config);
}
return config;
},
// On request failure
requestError: function (rejection) {
$log.error(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response failture,响应拦截
responseError: function (response) {
$log.error(response); // Contains the data about the error.
if (response.status === 401) {//状态码判断
//window.location = '/logoff';
Ares.logOff();
} else if (response.data) {//返回内容判断
if (response.data.name == 'TenantInactiveException') { aresMaintainUtil.goToTenantInactivePage();
}
          //发布一个订阅,导致弹出一个对话框
eventAggregator.publish(eventAggregator.events.ApiErrorHappened, response, 'apiInterceptor');
} else if (response.status === 0) {
var isSaasApi = true;
if (response.config && response.config.url.indexOf('//marketcenter') > -1) {
isSaasApi = false;
}
if (isSaasApi) {
aresMaintainUtil.ensureInMaintainMode().then(function (isInMaintainMode) {
if (isInMaintainMode) {
aresMaintainUtil.goToMaintainPage();
}
});
}
}
// Return the promise rejection.
return $q.reject(response);
}
};
}]);
//Aop拦截,对响应
webservices.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('apiInterceptor'); }]);

  注册订阅:

var subscribeEvents = function () {
eventAggregator.subscribe($scope, eventAggregator.events.ApiErrorHappened, onApiErrorHappened);
}; //弹出提示对话框
var onApiErrorHappened = function (event, args) {
if (args.data.name == 'MyOperationException'
|| args.data.name == 'CustomBusinessException') {
customDialog.info('系统提示', args.data.message);
}
};

ASP.NET Web API 异常处理 HttpResponseException 以及Angularjs获取异常信息并提示的更多相关文章

  1. 在 ASP.NET Web API 中使用 Attribute 统一处理异常

    并非所有的异常都需要 try-catch 进行重复的处理,这会导致大量的重复性代码,一旦后续系统出现异常处理机制的修改,随着代码量增多,修改也会变的更加困难. ASP.NET Web API 中特别增 ...

  2. ASP.NET Web API系列教程目录

    ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...

  3. ASP.NET Web API系列教程(目录)(转)

    注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...

  4. Implement JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1 Part 3 (by TAISEER)

    http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-an ...

  5. [转]ASP.NET Web API系列教程(目录)

    本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...

  6. 剖析Asp.Net Web API路由系统---WebHost部署方式

    上一篇我们剖析了Asp.Net路由系统,今天我们再来简单剖析一下Asp.Net Web API以WebHost方式部署时,Asp.Net Web API的路由系统内部是怎样实现的.还是以一个简单实例开 ...

  7. Asp.Net Web API 2第七课——Web API异常处理

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文主要来讲解Asp.Ne ...

  8. 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理

    原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...

  9. 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(3)

    chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angula ...

随机推荐

  1. web框架--MVC、MTV

    一.MVC框架: MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式:[1] Model(模型)表示应用程序核心(比如数据库记 ...

  2. 强大的easygrid V7 ,可联系作者

    增加历史记录事件 修改bug 修改风格 演示绑定表达式 下载demo

  3. qt小程序

    hello: #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApp ...

  4. [Selenium Grid] 搭建Hub和Node环境

    Note : 先在Hub和Node的机器上安装好JDK,  IE浏览器,Chrome浏览器,Firefox浏览器 准备好红色框标示的东西: Hub.bat :启动Hub AllNodes.bat  : ...

  5. Python之路(第十九篇)hashlib模块

    一.hashlib模块 HASH Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列算法,变换成固定长度的输出,该输出就是散列值 ...

  6. 论坛:一对一关联映射/单向关联/两个类间,可以有两个(多个)关联关系/content为大文本类型/

    >>单向:只写一端的映射属性,另一端不写(有一端用不着);双向:两端都写映射属性 >>一对一关联有两类:一类基于主键的(一般不使用),一类基于外键的(重点学习): 外键:是一个 ...

  7. is not allowed to connect to this MySQL server解决办法

    GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'mypassword' WITH GRANT OPTION; myuser:代表你 ...

  8. centos nfs配置备忘

    [需求]web应用需要部署在两台机器,图片目录共用,MySQL共用. [环境]Server: 192.168.168.10Client: 192.168.168.20 [配置步骤]1.在两台机器上安装 ...

  9. python包与模块导入

    一 .module 通常模块为一个文件,直接使用import来导入就好了.可以作为module的文件类型有".py".".pyo".".pyc&quo ...

  10. 2016年3月31日_应化所群体Review

    Review目的: Phonegap的ble插件可以接收到设备发送的信息,但接收并在控制台显示的数据夏一鸣不知道是正确的数据,还是由于编码解码问题导致的乱码问题.此次Review要解决的问题即判断接收 ...