所以我有一个数据库,该数据库在其内部尚未找到值时填充,基本上是用C#编写的Web API,该Web API检查是否内部是否有值,如果然后,其null调用另一个Web服务,该服务将检索数据并将新记录插入数据库,并将新创建的记录返回给用户。代码是这样的:
[HttpGet ("{idDocument}")]
public async Task<IActionResult> GetPerson (string idDocument)
{
// Get the person record from the database
var person = await repository.GetPersonAsync (idDocument);
// if the record does not exist, return not found
if (person == null)
{
Person newPerson = await GetNewPersonFromRemoteServer(idDocument);
var result = mapper.Map<Person, PersonResource>(newPerson);
return Ok(result);
}
// Map the record to a resource to return to user
var resource = mapper.Map<Person, PersonResource> (person);
// return record resource to user
return Ok (resource);
}
private async Task<Person> GetNewPersonFromRemoteServer(string id)
{
Person newPerson = new Person();
string address = "http://remoteservice.serv/?id=";
string fullAddress = address + id;
try
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(new Uri(fullAddress));
string responseMessage = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
Person newPerson = JsonConvert.Deserialize<Person>(responseMessage);
repository.AddPersonAsync(newPerson);
await uow.CompleteAsync();
return newPerson;
}
return newPerson;
}
}
catch (Exception ex)
{
return newPerson;
}
}
但是,该服务有时可以正常工作,有时甚至是返回的null,即使我执行远程服务,我会得到正确的数据响应。我相信这与嵌套的异步/等待方法/函数有关,但我似乎无法找到更好的解决方案。任何帮助将不胜感激!
您的异常处理非常错误。现在您吞咽了例外。此外,您可以在致命的例外做到这一点。这是例外处理的致命罪,可以轻松解释任何奇怪的行为。
致命的例外后,您的程序应始终关闭。忽略它们只会导致更多的后续错误,这些错误是无法调试甚至预测的。
您应该阅读适当的例外处理。这是我经常链接的两篇文章:
- http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx
- http://www.codeproject.com/articles/9538/exception andling-best-best-practices-innet