C# 向自定义异常添加额外信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:00:58  来源:igfitidea点击:

Adding extra information to a custom exception

提问by

I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle.

我为一个可能出错的非常具体的问题创建了一个自定义异常。我从另一个系统接收数据,如果它在尝试解析该数据时爆炸,我会引发异常。在我的自定义异常中,我添加了一个名为“ResponseData”的字段,因此我可以准确跟踪我的代码无法处理的内容。

In custom exceptions such as this one, should that extra response data go into the exception "message"? If it goes there, the message could be huge. I kind of want it there because I'm using Elmah, and that's how I can get at that data.

在像这样的自定义异常中,额外的响应数据是否应该进入异常“消息”?如果它去那里,信息可能是巨大的。我有点想要它,因为我正在使用 Elmah,这就是我获取数据的方式。

So the question is either: - How can I get Elmah to record extra information from a field in a custom exception OR - Should extra exception details go into the "message" property?

所以问题是: - 我怎样才能让 Elmah 从自定义异常中的字段中记录额外信息,或者 - 额外的异常详细信息是否应该进入“消息”属性?

采纳答案by S?ren Kuklau

You shouldn't fill .Messagewith debug information, but rather with a concise, helpful piece of text.

您不应填写.Message调试信息,而应填写简洁、有用的文本。

http://msdn.microsoft.com/en-us/library/system.exception.message.aspx

http://msdn.microsoft.com/en-us/library/system.exception.message.aspx

The text of Message should completely describe the error and should, when possible, explain how to correct it.The value of the Message property is included in the information returned by ToString.

The Message property is set only when creating an Exception. If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture.

[..]

Notes to Inheritors:

The Message property is overridden in classes that require control over message content or format. Application code typically accesses this property when it needs to display information about an exception that has been caught.

The error message should be localized.

Message 的文本应该完整地描述错误,并在可能的情况下解释如何纠正它。Message 属性的值包含在 ToString 返回的信息中。

Message 属性仅在创建异常时设置。如果没有为当前实例的构造函数提供任何消息,系统将提供使用当前系统区域性格式化的默认消息。

[..]

继承人注意事项:

Message 属性在需要控制消息内容或格式的类中被覆盖。应用程序代码通常在需要显示有关已捕获异常的信息时访问此属性。

错误消息应该被本地化。

Response data does not qualify as a description.

响应数据不能作为描述。

Not being familiar with elmah, I can't tell you how to extend the Exceptionclass while using it. Does elmah implement its own subclass to Exception? Or an interface? Can you subclass it yourself?

不熟悉 elmah,我无法告诉您如何Exception在使用它时扩展该类。elmah 是否实现了自己的子类Exception?还是接口?你可以自己子类化吗?

回答by Danimal

I don't understand the question -- you're extending System.Exception, and you already added the Elmah field. That's where it belongs -- as a public property of the exception itself.

我不明白这个问题——您正在扩展 System.Exception,并且您已经添加了 Elmah 字段。这就是它所属的地方——作为异常本身的公共财产。

回答by George Mauer

I don't fully understand the question but you seem to be asking what to do with additional exception data, if that is not your question feel free to ignore this.

我不完全理解这个问题,但您似乎在问如何处理额外的异常数据,如果这不是您的问题,请随意忽略这一点。

I think an important question to ask is what exactly is the exception message for? It is not for knowing where the exception came from, the stack trace is for that; it is not to encapsulate an exception in a more general one, that should be done with the InnerException field; in the case where your exception is only raised from a particular place in your code it isn't even for describing what kind of error you had - thats what the type of the exception is for.

我认为要问的一个重要问题是异常消息究竟是什么?不是为了知道异常来自哪里,堆栈跟踪是为了那个;不是将异常封装在更通用的异常中,这应该通过 InnerException 字段来完成;在您的异常仅从代码中的特定位置引发的情况下,它甚至不是为了描述您遇到的错误类型——这就是异常的类型。

Generally I use the message field to provide simple, human-readable tips that a programmer that is not me, seeing this error for the first time can use to gain an understanding of the underlying system. I consider the message field to be appropriate for a short (one sentence) explanation, a hint as to how this error is frequently raised, or a reference to further reading.

通常,我使用消息字段提供简单的、人类可读的提示,非我的程序员第一次看到此错误时可以使用这些提示来了解底层系统。我认为 message 字段适合用于简短的(一个句子)解释、有关如何经常引发此错误的提示或进一步阅读的参考。

So, as far as I understand your question, I think that the best way to store this 'additional information' that is received from another system is as an InnerException. I don't know Elmah, but if it's worth its salt it will check for InnerExceptions and store them.

因此,据我了解您的问题,我认为存储从另一个系统收到的“附加信息”的最佳方式是 InnerException。我不知道 Elmah,但如果值得的话,它会检查 InnerExceptions 并存储它们。

回答by George Mauer

Elmah is a http module that records unhandled exceptions.

Elmah 是一个记录未处理异常的 http 模块。

I guess it's just a limitation of Elmah, since it doesn't store custom fields. I guess I'll have to ask those guys. I have the extra field in there for the response data, but Elmah does not store it.

我想这只是 Elmah 的一个限制,因为它不存储自定义字段。我想我得问问那些人。我在那里有用于响应数据的额外字段,但 Elmah 不存储它。

回答by Atif Aziz

In custom exceptions such as this one, should that extra response data go into the exception "message"?

在像这样的自定义异常中,额外的响应数据是否应该进入异常“消息”?

No, as S?ren already pointed out. However, your exception type could override ToStringand sensibly add the response data information there. This is a perfectly normal practice followed by many of the exception types in the BCL (Base Class Library) so you will not find yourself swimming against the tide. For example, have a look at the System.IO.FileNotFoundException.ToStringimplementation in SSCLI (Rotor):

不,正如S?ren 已经指出的那样。但是,您的异常类型可能会覆盖ToString并明智地在那里添加响应数据信息。这是 BCL(基类库)中的许多异常类型所遵循的完全正常的做法,因此您不会发现自己逆流而上。例如,看看SSCLI (Rotor)中的System.IO.FileNotFoundException.ToString实现:

public override String ToString()
{
    String s = GetType().FullName + ": " + Message;

    if (_fileName != null && _fileName.Length != 0)
        s += Environment.NewLine + String.Format(Environment.GetResourceString("IO.FileName_Name"), _fileName);

    if (InnerException != null)
        s = s + " ---> " + InnerException.ToString();

    if (StackTrace != null)
        s += Environment.NewLine + StackTrace;

    try
    {
        if(FusionLog!=null)
        {
            if (s==null)
                s=" ";
            s+=Environment.NewLine;
            s+=Environment.NewLine;
            s+="Fusion log follows: ";
            s+=Environment.NewLine;
            s+=FusionLog;
        }
    }
    catch(SecurityException)
    {

    }
    return s;
}

As you can see, it appends the content of FusionLogproperty, which represent extrainformation in case of assembly load failures.

如您所见,它附加了FusionLog属性的内容,这些内容表示在程序集加载失败的情况下的额外信息。

How can I get Elmah to record extra information from a field in a custom exception

如何让 Elmah 从自定义异常中的字段中记录额外信息

ELMAHstores the result of calling ToStringon an exception as the details of the error so if you have ToStringimplemented as prescribed, the information would get logged without further work. The only issue is that the logged detail will be unstructuredtext.

ELMAH将调用ToString异常的结果存储为错误的详细信息,因此如果您已ToString按规定实施,则无需进一步工作即可记录该信息。唯一的问题是记录的详细信息将是非结构化文本。

回答by Gabriel Isenberg

The Exception class contains a dictionary (named Data, I believe) that you can use to associate custom data with a vanilla exception.

Exception 类包含一个字典(我相信名为 Data),您可以使用它来将自定义数据与普通异常相关联。