【发布时间】:2021-08-16 15:08:24
【问题描述】:
以下是问题的症状,GetAsync 方法有问题。
考虑自定义异常:
[Serializable]
public class FooException : Exception
{
public FooException(string message) : base(message) { }
public FooException(string type, int key) : base(FormatMessage(type, key)) { }
public FooException(string type, string key) : base(FormatMessage(type, key)) { }
protected FooException(SerializationInfo info, StreamingContext context) : base(info, context) { }
private static string FormatMessage<T>(string type, T key)
{
return $"{type} not found for key '{key}'.";
}
}
当它在控制器中被抛出、捕获和解析时,我们会收到以下消息:
System.Net.Http.HttpRequestException : 将内容复制到流时出错。
我们可以通过遵循典型的异常模式来解决这个问题:https://docs.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-localized-exception-messages,并将格式移动到一个单独的类,如下所示:
public static class ExceptionMessageFormatter
{
public static string FormatMessage<T>(string type, T key)
{
return $"{type} not found for key '{key}'.";
}
}
然后是下面的异常模式:
[Serializable]
public class FooException : Exception
{
public FooException() { }
public FooException(string message) : base(message) { }
public FooException(string message, Exception inner) : base(message, inner) { }
protected FooException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
这是对我有用的解决方案,但我仍然不知道为什么最初的异常没有像我们预期的那样工作,为什么会这样? .NET 5 中是否存在错误?
【问题讨论】:
-
A) 您的第一个示例没有
[Serializable],这是 C+P 错误,还是您的实际代码中缺少它? B)您的第二个示例没有调用消息格式化程序,这是 C+P 错误吗? -
是的@Neil,这是一个 C&P 错误,原因是我已将格式化程序从类中取出,因此调用者将使用它并改为解析字符串
-
你是说原始异常代码在类上有 [Serializable] 吗?错误消息表明它没有。
-
是的,我现在已经编辑了原始问题,谢谢
-
很不清楚 type 和 key 在建议的解决方法中可能来自哪里。当然,真正的问题在于您用来显示或记录异常的任何代码。除非它也显示异常的 InnerException,否则你什么都不知道。