如何吞咽...具有特定原因的例外 [英] How to swallow ... exception with specific reason

查看:45
本文介绍了如何吞咽...具有特定原因的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种方法中

    public static void Detach()
    {
        try
        {
            using (var master = new DataContext(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True"))
            {
                master.ExecuteCommand(string.Format("ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", DatabaseFile));
                master.ExecuteCommand(string.Format("exec sp_detach_db '{0}'", DatabaseFile));
            }
        }
        catch (Exception e)
        {
           ... // add to log
        }
    }

我可以收到例外

System.Data.SqlClient.SqlException(0x80131904):数据库blablabla.mdf不存在.提供有效的数据库名称.要查看可用的数据库,请使用sys.databases.

System.Data.SqlClient.SqlException (0x80131904): The database 'blablabla.mdf' does not exist. Supply a valid database name. To see available databases, use sys.databases.

如果未连接数据库时调用 Detach(),则会发生这种情况.

This happens if Detach() is called when database is not attached.

我的问题是:如何仅吞下此特定消息以避免将其记录下来?

文本可能已本地化,因此无法正常工作

Text may be localized, so this won't work

if(!(e is SqlException && e.Message.Contains("Supply a valid database name"))) 
    ... // log 

我不确定错误代码在此特定情况下是否唯一(Google证明了这一点)

I am not sure if error code is unique for this specific case (google proves it?)

if(!(e is SqlException && e.Message.Contains("0x80131904"))) 
    ... // log 

我当然可以做

try { ... } catch {}

但是后来我没有机会记录出乎意料的了,这可能会帮助我解决出现的问题.

But then I have no chance to get into log something unexpected, what may help me to solve problem in case it appears.

推荐答案

您不想检查消息-您想检查特定于SQL的号码.您可以使用 SqlException.Number 属性.

You don't want to check the message - you want to check the SQL specific number. You can use the SqlException.Number property for this.

我会使用:

// I think this is right, based on
// http://technet.microsoft.com/en-us/library/cc645936(v=sql.105).aspx
private const int DatabaseDoesNotExistCode = 15010;
...
catch (SqlException e)
{
    if (e.Number != DatabaseDoesNotExistCode)
    {
        ...
    }
}

(我通常不会捕获普通的 Exception ...,但这可能是另一回事.)

(I would typically not catch plain Exception... but that's probably a different matter.)

这篇关于如何吞咽...具有特定原因的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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