ASP.NET Web API 异常处理 HttpResponseException 以及Angularjs获取异常信息并提示
一、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获取异常信息并提示的更多相关文章
- 在 ASP.NET Web API 中使用 Attribute 统一处理异常
并非所有的异常都需要 try-catch 进行重复的处理,这会导致大量的重复性代码,一旦后续系统出现异常处理机制的修改,随着代码量增多,修改也会变的更加困难. ASP.NET Web API 中特别增 ...
- ASP.NET Web API系列教程目录
ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...
- ASP.NET Web API系列教程(目录)(转)
注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...
- 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 ...
- [转]ASP.NET Web API系列教程(目录)
本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...
- 剖析Asp.Net Web API路由系统---WebHost部署方式
上一篇我们剖析了Asp.Net路由系统,今天我们再来简单剖析一下Asp.Net Web API以WebHost方式部署时,Asp.Net Web API的路由系统内部是怎样实现的.还是以一个简单实例开 ...
- Asp.Net Web API 2第七课——Web API异常处理
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文主要来讲解Asp.Ne ...
- 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...
- 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(3)
chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angula ...
随机推荐
- 03. pt-config-diff
pt-config-diff h=192.168.100.101,P=3306,u=admin,p=admin h=192.168.100.102,P=3306,u=admin,p=admin pt- ...
- vuejs导航条动态切换active状态
用一个数组存导航条,用v-for循环它,这样可以减少代码,二可以使用它的下标来判断高亮,三还可以获取后端的导航信息来遍历 重点是在:routerLink(index, path)函数,传入当前点击的下 ...
- 搭建java环境和java学习
https://blog.csdn.net/fishe_r/article/details/18863447 其中的 java配置文件用: { "shell_cmd": " ...
- 安装linux子系统, 如何用win10 里面的linux子系统来进行通信
cd /mnt/d/linux_share即可 就把linux_share这个目录挂载到linux里面了.这样windows和linux可以同时修改和访问这个文件夹里面的内容. 安装:cmd中输入ba ...
- (xxx.55).toFixed(1) 无法正确进位处理
参考:https://juejin.im/post/5a11a9fef265da43284073b4?utm_medium=fe&utm_source=weixinqun 根本原因在于2.55 ...
- 提升HTML5的性能体验系列之三 流畅下拉刷新和上拉
下拉刷新 为实现下拉刷新功能,大多H5框架都是通过DIV模拟下拉回弹动画,在低端android手机(Android4.4以下)上,DIV动画经常出现卡顿现象(特别是图文列表的情况).解决方案还是web ...
- Ajax在jQuery中的应用 (4)向jsp提交表单数据
ajax技术带给我们的是良好的用户体验,同时,使用jquery可以简化开发,提高工作效率. 下面就介绍一下大致的开发步骤. 工具/原料 本文中使用的是 jquery-1.3.2.min.js 方法/步 ...
- 【转】C#异步的世界【下】
[转]C#异步的世界[下] 接上篇:<C#异步的世界[上]> 上篇主要分析了async\await之前的一些异步模式,今天说异步的主要是指C#5的async\await异步.在此为了方便的 ...
- PHP大数据处理要注意的
1. 传递值使用引用传递 $a = get_large_array(); pass_to_function(&$a); 这样是传递变量的引用而不是拷贝 2.将大数据存在类的变量中 class ...
- MySQL中使用SHOW PROFILE命令分析性能的用法整理
show profile是由Jeremy Cole捐献给MySQL社区版本的.默认的是关闭的,但是会话级别可以开启这个功能.开启它可以让MySQL收集在执行语句的时候所使用的资源.为了统计报表,把pr ...