【发布时间】:2014-07-17 08:35:30
【问题描述】:
当我向服务(我不拥有该服务)发送请求时,它可能会以请求的 JSON 数据或如下所示的错误进行响应:
{
"error": {
"status": "error message",
"code": "999"
}
}
在这两种情况下,HTTP 响应代码都是 200 OK,因此我无法使用它来确定是否存在错误 - 我必须反序列化响应以进行检查。 所以我有一些看起来像这样的东西:
bool TryParseResponseToError(string jsonResponse, out Error error)
{
// Check expected error keywords presence
// before try clause to avoid catch performance drawbacks
if (jsonResponse.Contains("error") &&
jsonResponse.Contains("status") &&
jsonResponse.Contains("code"))
{
try
{
error = new JsonSerializer<Error>().DeserializeFromString(jsonResponse);
return true;
}
catch
{
// The JSON response seemed to be an error, but failed to deserialize.
// Or, it may be a successful JSON response: do nothing.
}
}
error = null;
return false;
}
在这里,我有一个空的 catch 子句,它可能位于标准执行路径中,这是一种难闻的气味……嗯,不仅仅是难闻的气味:它很臭。
您知道“TryParse”响应以避免在标准执行路径中捕获的更好方法吗?
[编辑]
感谢Yuval Itzchakov 的回答,我改进了这样的方法:
bool TryParseResponse(string jsonResponse, out Error error)
{
// Check expected error keywords presence :
if (!jsonResponse.Contains("error") ||
!jsonResponse.Contains("status") ||
!jsonResponse.Contains("code"))
{
error = null;
return false;
}
// Check json schema :
const string errorJsonSchema =
@"{
'type': 'object',
'properties': {
'error': {'type':'object'},
'status': {'type': 'string'},
'code': {'type': 'string'}
},
'additionalProperties': false
}";
JsonSchema schema = JsonSchema.Parse(errorJsonSchema);
JObject jsonObject = JObject.Parse(jsonResponse);
if (!jsonObject.IsValid(schema))
{
error = null;
return false;
}
// Try to deserialize :
try
{
error = new JsonSerializer<Error>.DeserializeFromString(jsonResponse);
return true;
}
catch
{
// The JSON response seemed to be an error, but failed to deserialize.
// This case should not occur...
error = null;
return false;
}
}
我保留了 catch 子句……以防万一。
【问题讨论】: