SQL Server:使用原始异常编号重新引发异常 [英] SQL Server: Rethrow exception with the original exception number

查看:207
本文介绍了SQL Server:使用原始异常编号重新引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个存储过程中使用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指令。

推荐答案

谢谢你们的答案。从重新激发的信息中获取错误是我已经做的。

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对象中获取原始数字。在应用程序中捕获原始异常之后,我写下面的代码

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 Server:使用原始异常编号重新引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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