背景

架构之处必须考虑:如何处理异常?如何定义自己的异常体系?本文为了强化这个概念而写。

异常处理的两条“黄金定律”

自己抄袭的两条规律:

  1. 异常不能穿过“边界类”。
  2. 异常不能在没有恢复的情况下“吞掉”。

我们会将异常分为两类:“需要恢复”和“不需要恢复”,“需要恢复”的异常如果到达了边界类,就说明系统有BUG了,这类异常需要记录到日志。“不需要恢复”的异常需要进一步分为:“我们不能恢复”和“我们不期望恢复”,如果这类异常到达边界类,“我们不能恢复“的异常同样需要记录到日志,“我们不期望恢复”的异常则直接将异常信息显示给界面。一般采用AOP处理边界异常。

示例

AOP

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc; using Common.Logging;
using Happy.ExceptionHanding;
using Happy.Web.Mvc.Newtonsoft; namespace Happy.Web.Mvc.ExceptionHanding
{
/// <summary>
/// 处理应用程序未捕获的异常。
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class WriteExceptionResultAttribute : FilterAttribute, IExceptionFilter
{
/// <inheritdoc />
public void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
if (!FriendlyExceptionRegistry.IsFriendly(exception.GetType()))
{
LogManager.GetCurrentClassLogger().Error(exception);
}
filterContext.Result = CreateErrorResult(exception);
filterContext.ExceptionHandled = true;
} private static ActionResult CreateErrorResult(Exception exception)
{
var information = ExceptionInformationProviderRegistry.CreateInformation(exception); return new NewtonsoftJsonResult
{
Data = information
};
}
}
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using Happy.ExtentionMethods; namespace Happy.ExceptionHanding
{
/// <summary>
/// 异常信息提供者注册处。
/// </summary>
public static class ExceptionInformationProviderRegistry
{
private static readonly Dictionary<Type, IExceptionInformationProvider> _providers
= new Dictionary<Type, IExceptionInformationProvider>(); /// <summary>
/// 注册提供者。
/// </summary>
public static void Register<TException>(IExceptionInformationProvider provider)
where TException : Exception
{
Register(typeof(TException), provider);
} /// <summary>
/// 注册提供者。
/// </summary>
public static void Register(Type exceptionType, IExceptionInformationProvider provider)
{
exceptionType.MustNotNull("exceptionType");
provider.MustNotNull("provider"); _providers[exceptionType] = provider;
} public static Dictionary<string, object> CreateInformation(Exception exception)
{
exception.MustNotNull("exception"); var exceptionType = exception.GetType(); var information = CreateDefaultInformation(exception); if (_providers.ContainsKey(exceptionType))
{
var extInformation = _providers[exceptionType].CreateInformation(exception); foreach (var item in extInformation.ToDictionary())
{
information[item.Key] = item.Value;
}
}
else
{
if (FriendlyExceptionRegistry.IsFriendly(exception.GetType()))
{
information["exception"] = Resource.Messages.Msg_DefaultExceptionMessage;
}
} return information;
} private static Dictionary<string, object> CreateDefaultInformation(Exception exception)
{
return new Dictionary<string, object>
{
{ "success", false },
{ "exception", exception.GetType().Name },
{ "message",exception.Message }
};
}
}
}

备注

放弃继续玩 GO 的一个原因就是:GO 的异常处理太不爽了,或者是我自己的原因,不够 OPEN。

.NET:异常处理的两条“黄金定律”,求批!的更多相关文章

  1. 《转》前端性能优化----yahoo前端性能团队总结的35条黄金定律

    除了自己总结:1. 减少http请求,2.压缩并优化js/css/image 3.尽量静态页面,从简原则 4.代码规范(详见:个人知识体系思维导图) 从yahoo 新学到的: 网页内容 减少http请 ...

  2. 前端性能优化----yahoo前端性能团队总结的35条黄金定律

    转自 http://www.cnblogs.com/lei2007/archive/2013/08/16/3262897.html

  3. c编程:求出4&#215;4矩阵中最大和最小元素值及其所在行下标和列下标,求出两条主对角线元素之和。

    //求出4×4矩阵中最大和最小元素值及其所在行下标和列下标,求出两条主对角线元素之和 #include <stdio.h> int main() { int sum=0; int max, ...

  4. C++ 根据两点式方法求直线并求两条直线的交点

    Line.h #pragma once //Microsoft Visual Studio 2015 Enterprise //根据两点式方法求直线,并求两条直线的交点 #include"B ...

  5. 求空间内两条直线的最近距离以及最近点的坐标(C++)

    关键词:空间几何 用途:总有地方会用到吧 文章类型:C++函数展示 @Author:VShawn(singlex@foxmail.com) @Date:2016-11-19 @Lab: CvLab20 ...

  6. Intersecting Lines--POJ1269(判断两条直线的关系 && 求两条直线的交点)

    http://poj.org/problem?id=1269 我今天才知道原来标准的浮点输出用%.2f   并不是%.2lf  所以wa了好几次 题目大意:   就给你两个线段 然后求这两个线段所在的 ...

  7. 全是干货!UI设计的30条黄金准则!

    http://www.wex5.com/portfolio-items/js-1/ 全是干货!UI设计的30条黄金准则!   总的来说,好的UI界面有几个特征:简洁.便利.目标明确.人性化.字面上看这 ...

  8. 两条直线(蓝桥杯)二分枚举+RMQ

    算法提高 两条直线   时间限制:1.0s   内存限制:256.0MB        问题描述 给定平面上n个点. 求两条直线,这两条直线互相垂直,而且它们与x轴的夹角为45度,并且n个点中离这两条 ...

  9. 判断两条直线的位置关系 POJ 1269 Intersecting Lines

    两条直线可能有三种关系:1.共线     2.平行(不包括共线)    3.相交. 那给定两条直线怎么判断他们的位置关系呢.还是用到向量的叉积 例题:POJ 1269 题意:这道题是给定四个点p1, ...

随机推荐

  1. mongodb与mysql传统的关系数据库区别

    转自:易百教程 MongoDB中的数据具有灵活的模式.文档在同一集合,但它们不需要具有相同的字段或结构集合,集合文档中的公共字段可以包含不同类型的数据. MongoDB中的数据具有灵活的模式.与SQL ...

  2. hdu 5894(组合数取模)

    hannnnah_j’s Biological Test Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K ...

  3. [笔记]用gdb调试core dump

    总是隔一段时间才写一次C++,有些东西老是用完就忘了……记一下如何用gdb来调试core dump免得到时候又忘记. 首先需要设置core file的大小,默认是0所以不设不会生成core file ...

  4. C#中泛型的使用

    1. List<T> 2. Dictionary<TKey, TValue> 命名空间:using System.Collections.Generic; 普通数组:在声明时必 ...

  5. C++快速文件输入输出

    转载请注明: 仰望高端玩家的小清新 http://www.cnblogs.com/luruiyuan/ C语言可以获得接近汇编的性能,而输入输出常常是最为耗时的过程,因此可以使用 C 语言中的 fre ...

  6. Python类总结-多态及鸭子类型

    Python天生支持多态. 什么是多态: 一类事务的多种形态. 多态的一个例子 class Alipay(): def pay(self,money): print('用支付宝支付了%s元' % mo ...

  7. Mybatis使用入门

    一.Mybatis简介 1.传统JDBC的不足 我们首先看一下JDBC的一般操作流程.比如,我想从user表中获取根据name获取数据,下面是传统JDBC代码: package lkb.webchat ...

  8. java反射,代码优化

    java的反射机制属实强大,能解决好些问题 在接手别人写的代码的时候,有一个bean类的get方法特别low,我都看不下去 重复代码写五遍,我都觉得太不合理.之后将其中代码抽取出来修改了下. publ ...

  9. oracle 查询重复纪录

    DELETE FROM xx where aa in(select aa from xx group by aa having count(aa) >1) and rowid in (selec ...

  10. django配置templates、static、media和连接mysql数据库

    1.模板文件 # =======templates配置======= if os.path.exists(os.path.join(BASE_DIR, 'templates')) is False: ...