[英]How can I tell my method to ignore an exception and continue running?
how can I prevent an error in one part of my controller method from causing the whole method from returning a 500 error?如何防止控制器方法的一部分错误导致整个方法返回 500 错误?
I have this controller method that should delete a row in my database:我有这个控制器方法应该删除我的数据库中的一行:
// 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;
}
In the method, you can see I check for an Id called faunaList.EcosystemId
.在该方法中,您可以看到我检查了一个名为
faunaList.EcosystemId
的 Id。
If that exists, then I try to delete it.如果存在,那么我会尝试删除它。
However, if the EcosystemId
doesn't exist in the FaunaList_EcosystemList table, it throws this error in the browser:但是,如果 FaunaList_EcosystemList 表中不存在
EcosystemId
,则会在浏览器中抛出此错误:
DELETE https://sci-measure.xyz.gov/api/FaunaLists/TTE37B02-7624-4ED5-B62D-B7832C0D7E60 net::ERR_FAILED 500删除https://sci-measure.xyz.gov/api/FaunaLists/TTE37B02-7624-4ED5-B62D-B7832C0D7E60 net::ERR_FAILED 500
How can I ignore that error and just let the rest of the method continue to execute?我怎样才能忽略该错误并让方法的其余部分继续执行?
Thanks!谢谢!
When you write try-catch block like so:当你像这样写 try-catch 块时:
try{
//your code here
}
catch(Exception){
//your code here
}
It will catch every exception.它会捕获所有异常。
If you only want to catch one certain exception, you can specify that in the catch like so:如果你只想捕获一个特定的异常,你可以像这样在 catch 中指定它:
try{
// your code here
}
catch(SpecificException){
// your code here
}
This code will catch the specific exception and ignore others.此代码将捕获特定异常并忽略其他异常。
Or you can create a try-catch block for the if statement and write the continue
keyword and it will continue with the code.或者您可以为 if 语句创建一个 try-catch 块并编写
continue
关键字,它将继续执行代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.