How to determine if an exception is of a particular type

前端 未结 5 1096
Happy的楠姐
Happy的楠姐 2021-02-01 00:21

I have a piece of try catch code:

try 
{
    ...
}
catch(Exception ex) 
{
    ModelState.AddModelError(
        \"duplicateInvoiceNumberOrganisation\", \"The com         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 01:00

    before your current catch add the following:

    catch(DbUpdateException ex)
    {
      if(ex.InnerException is UpdateException)
      {
        // do what you want with ex.InnerException...
      }
    }
    

    From C# 6, you can do the following:

    catch(DbUpdateException ex) when (ex.InnerException is UpdateException)
    {
        // do what you want with ex.InnerException...
    }
    

提交回复
热议问题