一、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. Windows下war包部署到Linux下Tomcat出现的问题

    最近,将Windows下开发的war包部署到Linux下的Tomcat时报了一个错误:tomcat error in opening zip file.按理说,如果正常,当把war包复制到webapp ...

  2. Luogu 2467[SDOI2010]地精部落 - DP

    Solution 这题真秒啊,我眼瞎没有看到这是个排列 很显然, 有一条性质: 第一个是山峰 和 第一个是山谷的情况是一一对应的, 只需要把每个数 $x$  变成 $n-x+1$ 然后窝萌定义数组 $ ...

  3. MySQL 快速复数据库的方法

    为了方便快速复制一个数据库,可以用以下命令将db1数据库的数据以及表结构复制到newdb数据库 创建新的数据库 #mysql -u root -p123456 mysql>CREATE DATA ...

  4. laravel错误1071 Specified key was too long; max key length is 1000 bytes

    Laravel 5.5 环境,php artisan migrate 之后,出现错误如题. 检查了一下,代码是这样的: $table->increments('id'); $table-> ...

  5. [Hbase]Hbase知识大全

    HBase简介 是一个构建在HDFS上的分布式列存储系统:HBase是基于Google BigTable模型开发的,典型的key/value系统:HBase是Apache Hadoop生态系统中的重要 ...

  6. Sliding Window Maximum LT239

    Given an array nums, there is a sliding window of size k which is moving from the very left of the a ...

  7. openssl 连接 https(nginx)

    参考源码路径  demos\ssl #include <stdio.h> #include <string.h> #include <stdlib.h> #incl ...

  8. .net判断当前时间是否在工作时间段内

    整理代码,判断当前时间是否在配置的工作时间段内,代码如下: public static bool getTimeSpan(string _strWorkingDayAM, string _strWor ...

  9. Mysql 常用增删改查命令集合教程

    创建:create      插入:insert 更新:update  查询:select 删除:delete 修改:alter     销毁:drop 创建一个数据库: create databas ...

  10. 【Redis】使用Jedis操作Redis

    Jedis介绍 jedis就是集成了redis的一些命令操作,封装了redis的java客户端. Jedis使用 使用jedis需要引入jedis的jar包,下面提供了maven依赖 jedis.ja ...