Catch SQL raise error in C#

梦想的初衷 提交于 2019-11-28 19:16:58

RAISERRORs with a SEVERITY value under or equal to 10 are not caught on the C# side because I suppose they are considered just warnings as you can see from the list at Database Engine Error Severity

SEVERITY values between 11 and 16 are errors that can be corrected by the user, so, for example, you can try with:

RAISERROR('Already exist',16,1)

Otherwise you could choose another error code from from the list above or, if you really need it, prepare your own custom error message using sp_addmessage.

Your if statement is where things fail. Assuming that the first error in the collection is indeed the one you are looking for (it might not be).

SqlError.Number is not the value that you set in RAISERROR.

Use SqlError.Class to retrieve the severity of the error, or SqlError.State to check the state (both are -10 in your example. so difficult to tell which out you mean):

catch (SqlException ex)
{
    bResult = false;                   
    if (ex.Errors[0].Class == -10)
    {
        CommonTools.vAddToLog("bInsertNewUser", "ManageUsers", ex.Message);
        if ((savePoint != null))
            savePoint.Rollback();
    }
} 

Use an error code within 11-16, or just use 16 for a "general" case.

RAISERROR('Already exists',16,1)

Why? Here's my summary of https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities?view=sql-server-2017:

SQL RAISERROR -> C#:

  • 0-10 = fyi*
  • 11-16 = you can fix it**
  • 17-19 = get admin help
  • 20-24 = definitely get admin help***

*(don't throw anything) ┬──┬

**(16 = general)

***(fatal error)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!