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 ...
随机推荐
- 单细胞RNA测序技术之入门指南
单细胞RNA测序技术之入门指南 [字体: 大 中 小 ] 时间:2018年09月12日 来源:生物通 编辑推荐: 在这个飞速发展的测序时代,DNA和RNA测序已经逐渐成为“实验室中的家常菜”.若要 ...
- Windows 修改的hosts记录没有效果
windows修改的hosts记录没有效果,新添加的也没有效果. 检查DNS设置相关的均正常, <Dns client为此计算机解析和缓冲域名系统 (DNS) 名称.> 为此计算机注册并更 ...
- pycharm和anaconda
借鉴其他博文和亲自操作做一简要的总结: anaconda是python中一个管理包很好用的工具,可以轻松实现python中的各种包的管理.相信大家会有这样的体验,在pycharm中也是有自动搜索和下载 ...
- visual studio 修改注释快捷键,和断点
修改成alt+3和alt+4.效果不错 修改插入断点快捷键.这样按F12 就可以插入删除断点了.很爽 tab是批量加缩进 shift+tab 是批量减缩进
- 不立flag了……
当天刚说再也不想下这游戏了,后来和女友聊了会天视了会屏又动摇了..后悔和她那么计较这些小事,可能玩游戏时生气时就想不起来那么多事了吧..于是游戏过两天就又下回来了.. 这两天培训课程也是很快的感觉,昨 ...
- 解决ubuntu常见问题
cd /usr/local/hadoop 1. bash: cd: ~:Permission denied 报错:bash: cd: /usr/local/hadoop:Permission deni ...
- wireshark源码分析 一
因为手头的项目需要识别应用层协议,于是想到了wireshark,打算在项目中集成wireshark协议分析代码.在官网上下了最新版的wireshark源代码,我的天啊,200多M,这么多代码文件怎么看 ...
- Controller异步模式
转载: https://blog.csdn.net/yingxiake/article/details/51193319 因为服务器请求处理线程的总数是有限的,如果类似的请求多了,所有的处理线程处于阻 ...
- 【Java】JavaWeb 登录检查及界面跳转
场景 一般javaweb网站都有用户登录,而有一些操作必须用户登录才能进行,常见流程:用户请求-->后台判断是否登录-->没登录跳转到登录界面,登录用户正常操作 解决思路 在用过滤器过滤请 ...
- RNN模型(递归神经网络)简介
有些任务可以通过MLP多层感知器的神经网络,CNN卷积神经网络解决,因为那些任务内部的每一个前后无关联,无顺序,如MNIST手写数字子集,CIFAR子集等. 但是在自然语言处理中,每个字的前后有语义联 ...