我想用附加信息修改Message
属性。Exception
例如生成SQL
自EF
.
但我不想失去原来的任何东西Exception
。这将使我失去stacktrace
:
catch (Exception ex)
{
throw ex;
}
这些Exception
来自数据层。我想要throw
他们,以便他们可以使用Elmah
.
我有哪些选择?
如果你想添加一些东西,你可以把它包装在另一个异常中:
catch( Exception ex)
{
throw new Exception("my new message",ex);
}
您将能够使用完整的堆栈跟踪访问内部异常
定义您的自定义异常类,并将原始异常作为内部异常,并抛出包装的异常:
public class CustomException : Exception
{
public CustomException()
: base()
{
}
public CustomException(string message)
: base(message)
{
}
public CustomException(string message, Exception innerException)
: base(message, innerException)
{
}
//...other constructors with parametrized messages for localization if needed
}
catch (Exception ex)
{
throw new CustomException("Something went wrong", ex);
}
当然,它的名称应该相应地改变。这样,您就可以完全控制域中使用的异常,并且不会丢失原始 throw 中的任何信息。
具有良好类名的自定义异常非常有帮助,尤其是在大型项目中。它们有助于在许多简单情况下从一开始就诊断问题,而无需阅读异常的详细信息和调试。只有当一些真正复杂的问题发生时才需要后者。因此,扔掉Exception
彼此包裹的裸实例似乎是一种不好的做法。
The short answer to your question is, you can't. An exception is effectively a fault report and as such represents an historical event. Historical events by nature are immutable therefore you can't (nor should want to) "modify" them.
Instead what you can do is add some context to the exception by catching it and throwing a new exception. This will allow you to attach additional diagnostic information and also pass in the original exception thus maintaining the entire fault trail.
I won't go into detail on how to write a custom/use exception as I have already written a detailed answer on this subject before. However, as an example, your handling code should end up looking something like
catch (SomeEntityFrameworkException ex)
{
throw new MyCustomException("Some additional info", ex);
}
我只会创建自己的异常,其中包含原始异常和您想要的任何其他信息,在您的 catch 块中创建新异常并抛出它
做就是了:
catch (Exception ex)
{
throw;
}
这会进一步传递异常而不重新抛出它,并保留上下文。