简体   繁体   中英

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?

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 .

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:

DELETE 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{
 //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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM