[英]How can I tell my method to ignore an exception and continue running?
如何防止控制器方法的一部分错误导致整个方法返回 500 错误?
我有这个控制器方法应该删除我的数据库中的一行:
// DELETE: api/FaunaLists/5
[HttpDelete("{id}")]
public async Task<ActionResult<FaunaList>> DeleteFaunaList(string id)
{
// delete any associated references in FaunaList_EcosystemList table
// if that table doesn't have any references, this whole method throws a 500 error :(
if (faunaList.EcosystemId != null)
{
faunaEcosystemRef = _context.FaunaList_EcosystemList.Where(x => x.EcosystemId == faunaList.EcosystemId).ToList();
_context.FaunaList_EcosystemList.RemoveRange(faunaEcosystemRef);
}
try
{
_context.FaunaList.Remove(faunaList);
await _context.SaveChangesAsync();
}
catch (Exception e)
{
Message = _loggingMessage.GetLogException(this.GetType().Name.ToString(), ControllerActions.Exception, "FaunaList DELETE", id.ToString(), e.InnerException.ToString());
_logger.LogCritical(Message);
return BadRequest("Error when saving database changes. See error details.");
}
return faunaList;
}
在该方法中,您可以看到我检查了一个名为faunaList.EcosystemId
的 Id。
如果存在,那么我会尝试删除它。
但是,如果 FaunaList_EcosystemList 表中不存在EcosystemId
,则会在浏览器中抛出此错误:
删除https://sci-measure.xyz.gov/api/FaunaLists/TTE37B02-7624-4ED5-B62D-B7832C0D7E60 net::ERR_FAILED 500
我怎样才能忽略该错误并让方法的其余部分继续执行?
谢谢!
当你像这样写 try-catch 块时:
try{
//your code here
}
catch(Exception){
//your code here
}
它会捕获所有异常。
如果你只想捕获一个特定的异常,你可以像这样在 catch 中指定它:
try{
// your code here
}
catch(SpecificException){
// your code here
}
此代码将捕获特定异常并忽略其他异常。
或者您可以为 if 语句创建一个 try-catch 块并编写continue
关键字,它将继续执行代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.