1、ABP异常处理机制是通过过滤器实现的,我们查看的webAPI的异常处理,我们来看看他的源码,AbpApiExceptionFilterAttribute 继承ExceptionFilterAttribute, ITransientDependency

    public class AbpApiExceptionFilterAttribute : ExceptionFilterAttribute, ITransientDependency
{
/// <summary>
/// Reference to the <see cref="ILogger"/>.
/// </summary>
public ILogger Logger { get; set; } /// <summary>
/// Reference to the <see cref="IEventBus"/>.
/// </summary>
public IEventBus EventBus { get; set; } public IAbpSession AbpSession { get; set; } protected IAbpWebApiConfiguration Configuration { get; } /// <summary>
/// Initializes a new instance of the <see cref="AbpApiExceptionFilterAttribute"/> class.
/// </summary>
public AbpApiExceptionFilterAttribute(IAbpWebApiConfiguration configuration)
{
Configuration = configuration;
Logger = NullLogger.Instance;
EventBus = NullEventBus.Instance;
AbpSession = NullAbpSession.Instance;
} /// <summary>
/// Raises the exception event.
/// </summary>
/// <param name="context">The context for the action.</param>
public override void OnException(HttpActionExecutedContext context)
{
var wrapResultAttribute = HttpActionDescriptorHelper
.GetWrapResultAttributeOrNull(context.ActionContext.ActionDescriptor) ??
Configuration.DefaultWrapResultAttribute; if (wrapResultAttribute.LogError)
{
LogHelper.LogException(Logger, context.Exception);
} if (!wrapResultAttribute.WrapOnError)
{
return;
} if (IsIgnoredUrl(context.Request.RequestUri))
{
return;
} if (context.Exception is HttpException)
{
var httpException = context.Exception as HttpException;
var httpStatusCode = (HttpStatusCode) httpException.GetHttpCode(); context.Response = context.Request.CreateResponse(
httpStatusCode,
new AjaxResponse(
new ErrorInfo(httpException.Message),
httpStatusCode == HttpStatusCode.Unauthorized || httpStatusCode == HttpStatusCode.Forbidden
)
);
}
else
{
context.Response = context.Request.CreateResponse(
GetStatusCode(context),
new AjaxResponse(
SingletonDependency<IErrorInfoBuilder>.Instance.BuildForException(context.Exception),
context.Exception is Abp.Authorization.AbpAuthorizationException)
);
} EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
} protected virtual HttpStatusCode GetStatusCode(HttpActionExecutedContext context)
{
if (context.Exception is Abp.Authorization.AbpAuthorizationException)
{
return AbpSession.UserId.HasValue
? HttpStatusCode.Forbidden
: HttpStatusCode.Unauthorized;
} if (context.Exception is AbpValidationException)
{
return HttpStatusCode.BadRequest;
} if (context.Exception is EntityNotFoundException)
{
return HttpStatusCode.NotFound;
} return HttpStatusCode.InternalServerError;
} protected virtual bool IsIgnoredUrl(Uri uri)
{
if (uri == null || uri.AbsolutePath.IsNullOrEmpty())
{
return false;
} return Configuration.ResultWrappingIgnoreUrls.Any(url => uri.AbsolutePath.StartsWith(url));
}
}

我们看看他怎么处理异常的,他主要通过这个方法   SingletonDependency<IErrorInfoBuilder>.Instance.BuildForException(context.Exception)

首先我们先了解他返回的数据结构,AjaxResponse,他的基类是AjaxResponseBase,ABP所有接口的返回值的都是封装到这个类里

 public abstract class AjaxResponseBase
{
/// <summary>
/// This property can be used to redirect user to a specified URL.
/// </summary>
public string TargetUrl { get; set; } /// <summary>
/// Indicates success status of the result.
/// Set <see cref="Error"/> if this value is false.
/// </summary>
public bool Success { get; set; } /// <summary>
/// Error details (Must and only set if <see cref="Success"/> is false).
/// </summary>
public ErrorInfo Error { get; set; } /// <summary>
/// This property can be used to indicate that the current user has no privilege to perform this request.
/// </summary>
public bool UnAuthorizedRequest { get; set; } /// <summary>
/// A special signature for AJAX responses. It's used in the client to detect if this is a response wrapped by ABP.
/// </summary>
public bool __abp { get; } = true;
}

属性error主要用来封装错误信息的,他的属性包含如下

  /// <summary>
/// Error code.
/// </summary>
public int Code { get; set; } /// <summary>
/// Error message.
/// </summary>
public string Message { get; set; } /// <summary>
/// Error details.
/// </summary>
public string Details { get; set; } /// <summary>
/// Validation errors if exists.
/// </summary>
public ValidationErrorInfo[] ValidationErrors { get; set; }
ValidationErrors   这个属性用来保存验证信息的,他的主要属性如下
  /// <summary>
/// Validation error message.
/// </summary>
public string Message { get; set; } /// <summary>
/// Relate invalid members (fields/properties).
/// </summary>
public string[] Members { get; set; }

以上是异常信息返回的数据结构,我们来看看他的核心代码,主要是ErrorInfoBuilder

    public class ErrorInfoBuilder : IErrorInfoBuilder, ISingletonDependency
{
private IExceptionToErrorInfoConverter Converter { get; set; } /// <inheritdoc/>
public ErrorInfoBuilder(IAbpWebCommonModuleConfiguration configuration, ILocalizationManager localizationManager)
{
Converter = new DefaultErrorInfoConverter(configuration, localizationManager);
} /// <inheritdoc/>
public ErrorInfo BuildForException(Exception exception)
{
return Converter.Convert(exception);
} /// <summary>
/// Adds an exception converter that is used by <see cref="BuildForException"/> method.
/// </summary>
/// <param name="converter">Converter object</param>
public void AddExceptionConverter(IExceptionToErrorInfoConverter converter)
{
converter.Next = Converter;
Converter = converter;
}
}
 Converter.Convert(exception);  这个主要封装不同的异常信息,并且把它返回,返回类型是ErrorInfo,他的实现类是DefaultErrorInfoConvert,代码如下:
    internal class DefaultErrorInfoConverter : IExceptionToErrorInfoConverter
{
private readonly IAbpWebCommonModuleConfiguration _configuration;
private readonly ILocalizationManager _localizationManager; public IExceptionToErrorInfoConverter Next { set; private get; } private bool SendAllExceptionsToClients
{
get
{
return _configuration.SendAllExceptionsToClients;
}
} public DefaultErrorInfoConverter(
IAbpWebCommonModuleConfiguration configuration,
ILocalizationManager localizationManager)
{
_configuration = configuration;
_localizationManager = localizationManager;
} public ErrorInfo Convert(Exception exception)
{
var errorInfo = CreateErrorInfoWithoutCode(exception); if (exception is IHasErrorCode)
{
errorInfo.Code = (exception as IHasErrorCode).Code;
} return errorInfo;
} private ErrorInfo CreateErrorInfoWithoutCode(Exception exception)
{
if (SendAllExceptionsToClients)
{
return CreateDetailedErrorInfoFromException(exception);
} if (exception is AggregateException && exception.InnerException != null)
{
var aggException = exception as AggregateException;
if (aggException.InnerException is UserFriendlyException ||
aggException.InnerException is AbpValidationException)
{
exception = aggException.InnerException;
}
} if (exception is UserFriendlyException)
{
var userFriendlyException = exception as UserFriendlyException;
return new ErrorInfo(userFriendlyException.Message, userFriendlyException.Details);
} if (exception is AbpValidationException)
{
return new ErrorInfo(L("ValidationError"))
{
ValidationErrors = GetValidationErrorInfos(exception as AbpValidationException),
Details = GetValidationErrorNarrative(exception as AbpValidationException)
};
} if (exception is EntityNotFoundException)
{
var entityNotFoundException = exception as EntityNotFoundException; if (entityNotFoundException.EntityType != null)
{
return new ErrorInfo(
string.Format(
L("EntityNotFound"),
entityNotFoundException.EntityType.Name,
entityNotFoundException.Id
)
);
} return new ErrorInfo(
entityNotFoundException.Message
);
} if (exception is Abp.Authorization.AbpAuthorizationException)
{
var authorizationException = exception as Abp.Authorization.AbpAuthorizationException;
return new ErrorInfo(authorizationException.Message);
} return new ErrorInfo(L("InternalServerError"));
} private ErrorInfo CreateDetailedErrorInfoFromException(Exception exception)
{
var detailBuilder = new StringBuilder(); AddExceptionToDetails(exception, detailBuilder); var errorInfo = new ErrorInfo(exception.Message, detailBuilder.ToString()); if (exception is AbpValidationException)
{
errorInfo.ValidationErrors = GetValidationErrorInfos(exception as AbpValidationException);
} return errorInfo;
} private void AddExceptionToDetails(Exception exception, StringBuilder detailBuilder)
{
//Exception Message
detailBuilder.AppendLine(exception.GetType().Name + ": " + exception.Message); //Additional info for UserFriendlyException
if (exception is UserFriendlyException)
{
var userFriendlyException = exception as UserFriendlyException;
if (!string.IsNullOrEmpty(userFriendlyException.Details))
{
detailBuilder.AppendLine(userFriendlyException.Details);
}
} //Additional info for AbpValidationException
if (exception is AbpValidationException)
{
var validationException = exception as AbpValidationException;
if (validationException.ValidationErrors.Count > )
{
detailBuilder.AppendLine(GetValidationErrorNarrative(validationException));
}
} //Exception StackTrace
if (!string.IsNullOrEmpty(exception.StackTrace))
{
detailBuilder.AppendLine("STACK TRACE: " + exception.StackTrace);
} //Inner exception
if (exception.InnerException != null)
{
AddExceptionToDetails(exception.InnerException, detailBuilder);
} //Inner exceptions for AggregateException
if (exception is AggregateException)
{
var aggException = exception as AggregateException;
if (aggException.InnerExceptions.IsNullOrEmpty())
{
return;
} foreach (var innerException in aggException.InnerExceptions)
{
AddExceptionToDetails(innerException, detailBuilder);
}
}
} private ValidationErrorInfo[] GetValidationErrorInfos(AbpValidationException validationException)
{
var validationErrorInfos = new List<ValidationErrorInfo>(); foreach (var validationResult in validationException.ValidationErrors)
{
var validationError = new ValidationErrorInfo(validationResult.ErrorMessage); if (validationResult.MemberNames != null && validationResult.MemberNames.Any())
{
validationError.Members = validationResult.MemberNames.Select(m => m.ToCamelCase()).ToArray();
} validationErrorInfos.Add(validationError);
} return validationErrorInfos.ToArray();
} private string GetValidationErrorNarrative(AbpValidationException validationException)
{
var detailBuilder = new StringBuilder();
detailBuilder.AppendLine(L("ValidationNarrativeTitle")); foreach (var validationResult in validationException.ValidationErrors)
{
detailBuilder.AppendFormat(" - {0}", validationResult.ErrorMessage);
detailBuilder.AppendLine();
} return detailBuilder.ToString();
} private string L(string name)
{
try
{
return _localizationManager.GetString(AbpWebConsts.LocalizaionSourceName, name);
}
catch (Exception)
{
return name;
}
}
}

以上ABP异常处理的源码分析,代码中我们实际使用如下:

异常ABP异常分类

ABP的异常基类源代码 ABPException的源代码如下

   /// <summary>
/// Base exception type for those are thrown by Abp system for Abp specific exceptions.
/// </summary>
[Serializable]
public class AbpException : Exception
{
/// <summary>
/// Creates a new <see cref="AbpException"/> object.
/// </summary>
public AbpException()
{ } /// <summary>
/// Creates a new <see cref="AbpException"/> object.
/// </summary>
public AbpException(SerializationInfo serializationInfo, StreamingContext context)
: base(serializationInfo, context)
{ } /// <summary>
/// Creates a new <see cref="AbpException"/> object.
/// </summary>
/// <param name="message">Exception message</param>
public AbpException(string message)
: base(message)
{ } /// <summary>
/// Creates a new <see cref="AbpException"/> object.
/// </summary>
/// <param name="message">Exception message</param>
/// <param name="innerException">Inner exception</param>
public AbpException(string message, Exception innerException)
: base(message, innerException)
{ }
}

ABP通过ABPExceptionFilter拦截异常的源代码

    public class AbpExceptionFilter : IExceptionFilter, ITransientDependency
{
//日志记录
public ILogger Logger { get; set; } //事件总线
public IEventBus EventBus { get; set; } // 错误信息构建器
private readonly IErrorInfoBuilder _errorInfoBuilder; // AspNetCore 相关的配置信息
private readonly IAbpAspNetCoreConfiguration _configuration; public AbpExceptionFilter(IErrorInfoBuilder errorInfoBuilder, IAbpAspNetCoreConfiguration configuration)
{
_errorInfoBuilder = errorInfoBuilder;
_configuration = configuration; Logger = NullLogger.Instance;
EventBus = NullEventBus.Instance;
} public void OnException(ExceptionContext context)
{
if (!context.ActionDescriptor.IsControllerAction())
{
return;
} // // 获得方法的包装特性。决定后续操作,如果没有指定包装特性,则使用默认特性
var wrapResultAttribute =
ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
context.ActionDescriptor.GetMethodInfo(),
_configuration.DefaultWrapResultAttribute
); //需要记录日志
if (wrapResultAttribute.LogError)
{
LogHelper.LogException(Logger, context.Exception);
} //重构异常错误处理
if (wrapResultAttribute.WrapOnError)
{
HandleAndWrapException(context);
}
} /// <summary>
/// 包装异常
/// </summary>
/// <param name="context"></param>
protected virtual void HandleAndWrapException(ExceptionContext context)
{
//判断返回类型是否是objectresult,不是直接返回
if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
{
return;
} // 设置 HTTP 上下文响应所返回的错误代码,由具体异常决定。
context.HttpContext.Response.StatusCode = GetStatusCode(context); context.Result = new ObjectResult(
new AjaxResponse(
_errorInfoBuilder.BuildForException(context.Exception),
context.Exception is AbpAuthorizationException
)
); //// 触发异常处理事件
EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); // 处理完成,将异常上下文的内容置为空
context.Exception = null; //Handled!
} //根据不同的异常返回不同的status
protected virtual int GetStatusCode(ExceptionContext context)
{
if (context.Exception is AbpAuthorizationException)
{
return context.HttpContext.User.Identity.IsAuthenticated
? (int)HttpStatusCode.Forbidden //
: (int)HttpStatusCode.Unauthorized; //
} if (context.Exception is AbpValidationException)
{
return (int)HttpStatusCode.BadRequest; //
} if (context.Exception is EntityNotFoundException)
{
return (int)HttpStatusCode.NotFound; //
} return (int)HttpStatusCode.InternalServerError; //
}
}

ABP异常处理包装返回的结果结构,如果不想包装,请使用特性 DontWarpResult

{
"result": {
"totalCount": ,
"items": []
},
"targetUrl": null,
"success": true,
"error": null,
"unAuthorizedRequest": false,
"__abp": true
}

ABP正常接口返回的数据结构如下

public abstract class AjaxResponseBase
{
// 目标 Url 地址
public string TargetUrl { get; set; } // 接口调用是否成功
public bool Success { get; set; } // 当接口调用失败时,错误信息存放在此处
public ErrorInfo Error { get; set; } // 是否是未授权的请求
public bool UnAuthorizedRequest { get; set; } // 用于标识接口是否基于 Abp 框架开发
public bool __abp { get; } = true;
}

显示额外的异常处理,需要在模块预处理的代码中加入:

Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;

实时监听异常处理,如果需要发生报警,重写异常处理事件

public class ExceptionEventHandler : IEventHandler, ITransientDependency
{
/// /// Handler handles the event by implementing this method.
/// /// Event data
public void HandleEvent(AbpHandledExceptionData eventData)
{
Console.WriteLine($"当前异常信息为:{eventData.Exception.Message}");
}
}

ABP 异常处理 第四篇的更多相关文章

  1. c++异常处理第四篇---不使用try catch语句,使用Loki::ScopeGuard

    转载:神奇的Loki::ScopeGuard 2011-07-05 12:52:05 分类: C/C++ 转载:http://blog.csdn.net/fangqu/article/details/ ...

  2. abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)

    Introduction With AspNet MVC Web API EntityFramework and AngularJS 地址:https://aspnetboilerplate.com/ ...

  3. 从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点)

    从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点) 第一篇http://www.cnblogs.com/lyhabc/p/4678330.html第二篇http://www ...

  4. ABP框架实践基础篇之开发UI层

    返回总目录<一步一步使用ABP框架搭建正式项目系列教程> 说明 其实最开始写的,就是这个ABP框架实践基础篇.在写这篇博客之前,又回头复习了一下ABP框架的理论,如果你还没学习,请查看AB ...

  5. 第四篇 Entity Framework Plus 之 Batch Operations

    用 Entity Framework  进行 增,删,改.都是基于Model进行的,且Model都是有状态追踪的.这样Entity Framework才能正常增,删,改. 有时候,要根据某个字段,批量 ...

  6. 【第四篇】ASP.NET MVC快速入门之完整示例(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  7. 解剖SQLSERVER 第十四篇 Vardecimals 存储格式揭秘(译)

    解剖SQLSERVER 第十四篇    Vardecimals 存储格式揭秘(译) http://improve.dk/how-are-vardecimals-stored/ 在这篇文章,我将深入研究 ...

  8. 解剖SQLSERVER 第四篇 OrcaMDF里对dates类型数据的解析(译)

    解剖SQLSERVER 第四篇  OrcaMDF里对dates类型数据的解析(译) http://improve.dk/parsing-dates-in-orcamdf/ 在SQLSERVER里面有几 ...

  9. 深入理解javascript作用域系列第四篇——块作用域

    × 目录 [1]let [2]const [3]try 前面的话 尽管函数作用域是最常见的作用域单元,也是现行大多数javascript最普遍的设计方法,但其他类型的作用域单元也是存在的,并且通过使用 ...

随机推荐

  1. rabbitmq (三) 发布/订阅

    rabbitmq的目的并不是让生产者把消息直接发到队列里面去, 这样不能实现解耦的目的,也不利于程序的扩展. 所以就有交换机(exchanges)的概念. 交换机有几种类型:direct, topic ...

  2. 第一课了解SQL

    1.1 数据库基础 其实一直在使用这数据库,当你在邮箱中查询名字时,当在网站上进行搜索,在自动取款机上使用ATM卡,这些操作都是在使用数据库 1.1.1 数据库   数据库:保存有组织的数据的容器(通 ...

  3. QQ第三方登录(完结篇)

    书接上回,上回说到:这篇是代码篇 首先我们先来看一下我的母鹿(目录)吧 Connect2.1  是我们从下载的SDK,内容包含 其他文件在配置之后全部删除了! index.html 是我们点击登陆的页 ...

  4. Oracle 循环查询

    select * from sys_department start with departmentid = '0303e461-2454-4d5a-bfea-2cd5a4c064c6' connec ...

  5. js类的继承,es5和es6的方法

    存在的差异:1. 私有数据继承差异 es5:执行父级构造函数并且将this指向子级 es6:在构造函数内部执行super方法,系统会自动执行父级,并将this指向子级2. 共有数据(原型链方法)继承的 ...

  6. [UnityAPI]SerializedObject类 & SerializedProperty类

    以Image类为例 1.MyImage.cs using UnityEngine; using UnityEngine.UI; public class MyImage : Image { ; pro ...

  7. 浅读《视觉SLAM十四讲:从理论到实践》--操作1--初识SLAM

    下载<视觉SLAM十四讲:从理论到实践>源码:https://github.com/gaoxiang12/slambook 第二讲:初识SLAM 2.4.2 Hello SLAM(书本P2 ...

  8. ORM对象关系映射

    ORM 总结: ORM:对象关系映射 作用: 1.将定义数据库模型类--> 数据库表 2.将定义数据库模型类中的属性--->数据库表字段 3.将模型对象的操作(add,delete,com ...

  9. OpenGL中的渲染方式—— GL_TRIANGLE_STRIP

    OpenGL值绘制三角形的方式常用的有三种,分别是GL_TRIANGLES.GL_TRIANGLE_STRIP.GL_TRIANGLE_FAN,其效果如依次是: 从左起:第一个方式是GL_TRIANG ...

  10. leetcode142

    public class Solution { public ListNode detectCycle( ListNode head ) { if( head == null || head.next ...