Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 475|回复: 0

.NET:异常处理的两条“黄金定律”,求批!

[复制链接]
  • TA的每日心情
    奋斗
    2024-4-6 11:05
  • 签到天数: 748 天

    [LV.9]以坛为家II

    2034

    主题

    2092

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    705612
    发表于 2021-6-19 14:12:59 | 显示全部楼层 |阅读模式

    背景

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

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

    自己抄袭的两条规律:

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

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

    示例

    AOP

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.Web.Mvc;
     7 
     8 using Common.Logging;
     9 using Happy.ExceptionHanding;
    10 using Happy.Web.Mvc.Newtonsoft;
    11 
    12 namespace Happy.Web.Mvc.ExceptionHanding
    13 {
    14     /// <summary>
    15     /// 处理应用程序未捕获的异常。
    16     /// </summary>
    17     [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    18     public class WriteExceptionResultAttribute : FilterAttribute, IExceptionFilter
    19     {
    20         /// <inheritdoc />
    21         public void OnException(ExceptionContext filterContext)
    22         {
    23             var exception = filterContext.Exception;
    24             if (!FriendlyExceptionRegistry.IsFriendly(exception.GetType()))
    25             {
    26                 LogManager.GetCurrentClassLogger().Error(exception);
    27             }
    28             filterContext.Result = CreateErrorResult(exception);
    29             filterContext.ExceptionHandled = true;
    30         }
    31 
    32         private static ActionResult CreateErrorResult(Exception exception)
    33         {
    34             var information = ExceptionInformationProviderRegistry.CreateInformation(exception);
    35 
    36             return new NewtonsoftJsonResult
    37             {
    38                 Data = information
    39             };
    40         }
    41     }
    42 }
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 using Happy.ExtentionMethods;
     8 
     9 namespace Happy.ExceptionHanding
    10 {
    11     /// <summary>
    12     /// 异常信息提供者注册处。
    13     /// </summary>
    14     public static class ExceptionInformationProviderRegistry
    15     {
    16         private static readonly Dictionary<Type, IExceptionInformationProvider> _providers
    17             = new Dictionary<Type, IExceptionInformationProvider>();
    18 
    19         /// <summary>
    20         /// 注册提供者。
    21         /// </summary>
    22         public static void Register<TException>(IExceptionInformationProvider provider)
    23             where TException : Exception
    24         {
    25             Register(typeof(TException), provider);
    26         }
    27 
    28         /// <summary>
    29         /// 注册提供者。
    30         /// </summary>
    31         public static void Register(Type exceptionType, IExceptionInformationProvider provider)
    32         {
    33             exceptionType.MustNotNull("exceptionType");
    34             provider.MustNotNull("provider");
    35 
    36             _providers[exceptionType] = provider;
    37         }
    38 
    39         public static Dictionary<string, object> CreateInformation(Exception exception)
    40         {
    41             exception.MustNotNull("exception");
    42 
    43             var exceptionType = exception.GetType();
    44 
    45             var information = CreateDefaultInformation(exception);
    46 
    47             if (_providers.ContainsKey(exceptionType))
    48             {
    49                 var extInformation = _providers[exceptionType].CreateInformation(exception);
    50 
    51                 foreach (var item in extInformation.ToDictionary())
    52                 {
    53                     information[item.Key] = item.Value;
    54                 }
    55             }
    56             else
    57             {
    58                 if (FriendlyExceptionRegistry.IsFriendly(exception.GetType()))
    59                 {
    60                     information["exception"] = Resource.Messages.Msg_DefaultExceptionMessage;
    61                 }
    62             }
    63 
    64             return information;
    65         }
    66 
    67         private static Dictionary<string, object> CreateDefaultInformation(Exception exception)
    68         {
    69             return new Dictionary<string, object> 
    70             { 
    71                 { "success", false },
    72                 { "exception", exception.GetType().Name },
    73                 { "message",exception.Message }
    74             };
    75         }
    76     }
    77 }

    备注

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

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-25 08:15 , Processed in 0.070098 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表