如何确定异常是否是特定类型 [英] How to determine if an exception is of a particular type

查看:133
本文介绍了如何确定异常是否是特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段尝试代码:

try 
{
    ...
}
catch(Exception ex) 
{
    ModelState.AddModelError(
        "duplicateInvoiceNumberOrganisation", "The combination of organisation and invoice number must be unique");
}

对于这段代码,我试图在数据库中插入一条记录:dba已设置好,以便数据库检查重复项,如果有重复则返回错误。目前,您可以看到,无论发生什么错误,我都会向模型添加相同的错误。我想要它改变,所以这个错误只是添加到模型,如果它是由dba设置的重复错误引起的。

For this piece of code I'm trying to insert a record into a database: The dba has set it up so that the database checks for duplicates and returns an error if there are duplicates. Currently, as you can see, I'm adding the same error to the model no matter what error occurred. I want it changed so this error is only added to the model if it was caused by the duplicate error set up by the dba.

以下是我想要捕获的错误。注意它在内在的异常。任何人都可以告诉我如何专门抓住这一个?

Below is the error I want to catch. Note it's in the inner exception. Can anyone tell me how to specifically catch this one?

推荐答案

之前

before your current catch add the following:

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

这篇关于如何确定异常是否是特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆