SQL服务器:重新抛出异常与原来的异常编号 [英] SQL Server: Rethrow exception with the original exception number

查看:365
本文介绍了SQL服务器:重新抛出异常与原来的异常编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的存储过程try catch块,我有两个INSERT指令。

I am using a TRY CATCH block in a stored procedure where I have two INSERT instructions.

如果出现错误,CATCH块需要回滚所做的所有更改的关心和它工作得很好,除了一件事!

If something goes wrong, the CATCH block takes care of rolling back all changes made and it works fine, except one thing!

我的ASP.NET应用程序捕捉到的异常是数50000抛出SQLException这不是原来的号码! (我期待数是2627)

The exception caught by my ASP.NET application is a SqlException with number 50000. This is not the original number! (the number I was expecting was a 2627)

在异常的Message属性我可以看到原来的异常号和消息格式化。

In the Message property of the exception I can see the original exception number and message formated.

我怎样才能得到原始异常号?

How can I get the original exception number?

try
{
    // ... code
}
catch
(SqlException sqlException)
{
    switch (sqlException.Number)
    {
        // Name already exists
        case 2627:
            throw new ItemTypeNameAlreadyExistsException();

        // Some other error
        // As the exception number is 50000 it always ends here!!!!!!
        default:
            throw new ItemTypeException();
    }
}

现在已被使用的返回值。我想,我可以用一个输出参数,以获得异常号,但是是一个好主意?

Right now the return value is already being used. I guess that I could use an output parameter to get the exception number, but is that a good idea?

我能做些什么来获取异常号?谢谢

What can I do to get the exception number? Thanks

PS:这是必要的,因为我有两个INSERT说明

推荐答案

感谢你们的答案。从重新抛出excetpion的消息得到的错误是我已经做了。

Thank you guys for your answers. Getting the error from the message of the re-thrown excetpion was something I had already done.

@gbn我也喜欢GBN的答案,但我会坚持这个答案,因为它是效果最好的之一,我在这里张贴,希望这也将是对别人有用的。

@gbn I also liked the gbn answer, but I will stick to the this answer as it is the one that works best and I am posting it here hoping it will also be useful for others.

答案在应用程序中使用事务。如果我没有捕获异常在存储过程中我会在SQLException对象原来的号码。在应用程序中捕获原始异常后,我写了下面code

The answer is using transactions in the application. If I don't catch the exception in the stored procedure I will get the original number in the SqlException object. After catching the original exception in the application, I write the following code

transaction.Rollback();

否则:

transaction.Commit();

这是简单得多,比我预期的首先!

It's much simpler than I firstly expected!

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction.aspx

这篇关于SQL服务器:重新抛出异常与原来的异常编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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