是否有推荐的方法将错误消息保留在 Web 服务请求的对象中?
在一些示例中,我看到 Web 服务返回包含一些 HTTP 错误代码的包装类,其他则保存 .NET 异常消息。另一方面,有些示例返回普通对象或对象列表。
最佳答案
错误处理一开始可能会显得令人困惑。 official documentation is here 。但本质上,ServiceStack 尝试以一致的方式返回错误,以便您的客户端始终知道如何处理它们。您应该以正常的 C# 方式抛出异常,ServiceStack 会捕获这些异常并将其封装在 ResponseStatus 对象中,如下所示:
public class ResponseStatus
{
public string ErrorCode { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }
public List<ResponseError> Errors { get; set; }
}
因此,您将收到一个响应对象,其中包含一个名为 ResponseStatus
的属性,该属性具有上面填充的 ResponseStatus
对象。
注意事项:
仅当您在 ServiceStack AppHost Config 中启用
debug
模式时,才会包含StackTrace
属性。即:SetConfig(new HostConfig { DebugMode = true });
这将是您所引用的 .NET 异常,并且根据是否设置了
DebugMode
来有条件地显示。ResponseError
的Errors
列表仅在验证错误失败时填充。这将是验证错误的列表。这就是为什么您在某些示例中看到一个简单的错误响应(即不是验证错误),以及一个附加错误列表的响应(验证错误)。您还应该阅读有关 validation in the documentation 的部分。ResponseError
对象的格式是这样的:public class ResponseError { public string ErrorCode { get; set; } public string FieldName { get; set; } public string Message { get; set; } }
ResponseStatus
对象的ErrorCode
和Message
将从Errors
列表的第一项中获取.
让某些人感到困惑的是如何将 ResponseStatus
包含为预期响应请求的属性。
因此,假设您想返回一个 Person
对象,如下所示:
class Person
{
string FirstName { get; set; }
string LastName { get; set; }
}
如果返回此 Person
响应的请求引发验证异常,您可能会收到如下 JSON 响应:
{
"ResponseStatus": {
"ErrorCode": "ShouldNotBeEmpty",
"Message": "'FirstName' should not be empty",
"StackTrace": "..."
"Errors": [
{
"ErrorCode": "ShouldNotBeEmpty",
"FieldName": "FirstName",
"Message": "'FirstName' should not be empty"
},
{
"ErrorCode": "ShouldNotBeEmpty",
"FieldName": "LastName",
"Message": "'LastName' should not be empty"
},
]
}
}
请注意,此响应中不包含 Person 的响应对象,而只是包含 ResponseStatus 属性的对象。如果我们想包含带有状态的响应对象,我们必须这样声明我们的 person 类:
class PersonResponse
{
ResponseStatus ResponseStatus { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
}
然后,当抛出异常时,响应将包含响应对象及其状态:
{
"FirstName": "",
"LastName": "",
"ResponseStatus": {
...
ServiceStack 为您提供了对抛出异常时返回的错误格式的大量控制,您最好通读我上面链接到的官方文档来理解它。定制更像是一个高级主题。
关于c# - 使用 ServiceStack 处理错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805609/