Catch SQL raise error in C#

后端 未结 3 560
既然无缘
既然无缘 2020-12-25 11:50

I generate the raise error in SQL procedure:

RAISERROR(\'Already exist\',-10,-10)

but I can not catch it using the following co

3条回答
  •  春和景丽
    2020-12-25 12:36

    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();
        }
    } 
    

提交回复
热议问题