[英]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.