在没有 class 引用的情况下覆盖异常 class 和处理错误
Override Exception class and Handle error without class referencing
我想在一个地方处理所有错误而不引用 class。
查看我当前的结构。
public ActionResult Login(string returnUrl)
{
try
{
var a = 10;
var b = 0;
var c = a / b;
}
catch (Exception ex)
{
throw new LogEroor("", ex);
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
和我的错误处理 class。
public class LogEroor : Exception
{
public LogEroor(string message, Exception Ex) : base(message, Ex)
{
// error handling
}
}
My question
有什么方法可以在发生错误时使用 Ex 参数调用 LogError 方法,但我不想每次都调用此方法catch,就像我在这里做的那样。
这是典型的XY problem。您要解决的实际问题 X 解释为:
I want to log all exceptions that occur in my web application.
你的解 Y 是,解释为:
I will inherit from Exception, in which I will do the logging, and want any exception that is thrown to be converted to my exception type so it can be logged, without writing a try-catch block in all places where exceptions can occur.
现在您需要帮助解决问题 Y,但这完全是错误的方法。您可以使用 AppDomain.UnhandledException
event 来做到这一点,但您不应该这样做。
您的解决方案在 How do I log ALL exceptions globally for a C# MVC4 WebAPI app? 中:使用异常过滤器。
您希望如何在不指定的情况下调用方法甚至构造函数?你想要的根本没有意义,当然你所有的 classes 都必须引用通用异常 - class 如果它们高达 throw 一个。
您可以注册到 AppDomain.UnhandledExceptionHandler
,但是它是所有 not 处理的异常的通用处理程序。因此,与其捕获所有异常并通过 whrapping 再次抛出它们,不如使用以下方法:
AppDomain.UnhandledExceptionHandler += (sender, args) => { throw new LogError(args.ExceptionObject); };
但是这样你会在应用程序的最后一层异常处理中抛出异常。这意味着您抛出一个永远不会被捕获的异常,并且会使您的应用程序崩溃。为避免这种情况,请直接在该事件中实现您的日志记录。
我想在一个地方处理所有错误而不引用 class。
查看我当前的结构。
public ActionResult Login(string returnUrl)
{
try
{
var a = 10;
var b = 0;
var c = a / b;
}
catch (Exception ex)
{
throw new LogEroor("", ex);
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
和我的错误处理 class。
public class LogEroor : Exception
{
public LogEroor(string message, Exception Ex) : base(message, Ex)
{
// error handling
}
}
My question
有什么方法可以在发生错误时使用 Ex 参数调用 LogError 方法,但我不想每次都调用此方法catch,就像我在这里做的那样。
这是典型的XY problem。您要解决的实际问题 X 解释为:
I want to log all exceptions that occur in my web application.
你的解 Y 是,解释为:
I will inherit from Exception, in which I will do the logging, and want any exception that is thrown to be converted to my exception type so it can be logged, without writing a try-catch block in all places where exceptions can occur.
现在您需要帮助解决问题 Y,但这完全是错误的方法。您可以使用 AppDomain.UnhandledException
event 来做到这一点,但您不应该这样做。
您的解决方案在 How do I log ALL exceptions globally for a C# MVC4 WebAPI app? 中:使用异常过滤器。
您希望如何在不指定的情况下调用方法甚至构造函数?你想要的根本没有意义,当然你所有的 classes 都必须引用通用异常 - class 如果它们高达 throw 一个。
您可以注册到 AppDomain.UnhandledExceptionHandler
,但是它是所有 not 处理的异常的通用处理程序。因此,与其捕获所有异常并通过 whrapping 再次抛出它们,不如使用以下方法:
AppDomain.UnhandledExceptionHandler += (sender, args) => { throw new LogError(args.ExceptionObject); };
但是这样你会在应用程序的最后一层异常处理中抛出异常。这意味着您抛出一个永远不会被捕获的异常,并且会使您的应用程序崩溃。为避免这种情况,请直接在该事件中实现您的日志记录。