简体   繁体   English

从类库中抛出单个自定义异常

[英]Throw single custom exception from Class Library

How can I write a catch all exception handler in a Class Library project in C#, which will give the outside caller only one Custom Exception on any exception occurring in the library. 如何在C#中的类库项目中编写catch all all exception handler ,这将为外部调用者在库中发生的任何异常时只提供一个自定义异常。

Most nearest solution I found is to implement a Facade class, call low level classes from it, and write try..catch in every call from Facade which will throw single custom exception if any exception occurs underneath. 我找到的最接近的解决方案是实现一个Facade类,从中调用低级类,并在Facade的每次调用中编写try..catch ,如果下面发生任何异常,它将抛出单个自定义异常。

I searched for solutions, but got it only for Web Applications (using Application context for catching exceptions) eg How to implement one "catch'em all" exception handler with resume? 我搜索了解决方案,但只为Web应用程序(使用应用程序上下文捕获异常)得到它,例如如何用简历实现一个“catch'em all”异常处理程序?

I need to implement it at Class Library level or at consumer of library level, but good if that can be done by write minimum exception handling statements. 我需要在类库级别或库级别的使用者中实现它,但是如果可以通过编写最小异常处理语句来完成它。

You could use: 可以使用:

AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
    {
        var exception = e.ExceptionObject as Exception;
        if (exception != null && exception.Source == "MyLib")
        {
            // Do stuff here
        }
    };

But seriously, don't do it. 但说真的,不要这样做。 Exceptions shouldn't be handled this way, you should catch them locally. 不应该以这种方式处理异常,你应该在本地捕获它们。

您可以使用AppDomain.UnhandledException但请确保彻底阅读文档 - 有一些您无法处理的异常,它还取决于您使用的框架版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM