背景

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

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

自己抄袭的两条规律:

  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. linux c下输入密码不回显

    今天做一个登录程序,需要屏蔽掉密码,于是自己就在网上找资料,找到了一种和linux终端下输入密码方式相同的方法,不显示在终端,具体代码实现如下. #include<stdio.h> #in ...

  2. html学习-css

    1.css初识 css 中文解释:层叠样式表,把html比作骨骼的话,css就是衣服,他的外在都能通过css来修饰,js则是肌肉,能使html动起来.产生用户交互... 1.1css样式表类型 css ...

  3. 【严蔚敏】【数据结构题集(C语言版)】1.16 自大至小依次输出读入的三个整数X,Y,Z

    #include <stdio.h> #include<stdlib.h> int main() { int x,y,z,temp; scanf("%d%d%d&qu ...

  4. js屏蔽手机的物理返回键

    $(document).ready(function() { if (window.history && window.history.pushState) { $(window).o ...

  5. bzoj 1880 最短路径图

    #include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk mak ...

  6. NoSql数据库 设计上面的一些心得

    NoSql数据库这个概念听闻许久了,也陆续看到很多公司和产品都在使用,优缺点似乎都被分析的清清楚楚.但我心里一直存有一个疑惑,它的出现究竟是为了解决什么问题? 用户信息表,书籍信息表,用户为书籍打分信 ...

  7. 一个配置文件收集多个日志-if根据type类型判断

    1.同时收集/var/log/messages日志和secure日志 #vim /etc/logstash/conf.d/system.conf input { file { path => & ...

  8. python定制类(1):__getitem__和slice切片

    python定制类(1):__getitem__和slice切片 1.__getitem__的简单用法: 当一个类中定义了__getitem__方法,那么它的实例对象便拥有了通过下标来索引的能力. c ...

  9. 查找无序数组中第K大的数

    思路: 利用快速排序的划分思想 可以找出前k大数,然后不断划分 直到找到第K大元素 代码: #include <iostream> #include <algorithm> # ...

  10. js的循环

    1.for(){} 这种方法可能每个人都用过,不多说. 2.ES5的forEach myArray.forEach(function (value) { console.log(value); }); ...