从C#中的存储过程中捕获错误

我有一个存储过程,用于在登录期间validation用户。 如果成功则返回用户实体,这样做效果很好! 我的问题是,如果它不起作用,我会在SP中引发错误,如何捕获此错误并以最佳方式使用它? 现在我得到nullrefference,这是代码:存储过程:

ALTER PROCEDURE getEmployee ( @username nvarchar(50), @password nvarchar(50) ) AS DECLARE @Error_MSG nvarchar(50) BEGIN IF EXISTS (select * from Employee where eUsername = @username AND pword = @password) begin select * from Employee where eUsername = @username AND pword = @password END ELSE BEGIN SET @Error_MSG = 'Wrong password, or user doesnt exist' RAISERROR (@Error_MSG, 11,1) END END 

在代码中看起来像这样,SP就是getEmployee

 ActivityDatabaseDataContext dc = new ActivityDatabaseDataContext(); Employee emp; public bool logIn(string piUsername, string piPassword) { try { emp = dc.getEmployee(piUsername, piPassword).Single(); } catch (Exception ex) { errorMsg = ex.Message + ex.InnerException.Message; } if (emp != null) { AppHelper.AppHelper.setUser(emp); return true; } else { return false; } 

我的问题是我应该如何处理exception?

我通常不会从SP引发错误,除非它实际上是操作的系统问题。 输入错误的用户名和密码是一个用户问题,你只需要在接口级别处理一个问题,所以我将大部分SP丢弃并处理两个用例(返回1行或0行)业务层或接口代码。 如果为0行,则向客户端抛出“错误的用户名或密码”消息,如果为1,则登录。

 ALTER PROCEDURE getEmployee ( @username nvarchar(50), @password nvarchar(50) ) AS BEGIN select * from Employee where eUsername = @username AND pword = @password END 

您的InnerException可能为null。

您应该尝试捕获并处理特定的exception,在本例中为SqlExceptions 。

  ALTER PROCEDURE getEmployee ( @username nvarchar(50), @password nvarchar(50) ) AS BEGIN select * from Employee where eUsername = @username AND pword = @password END 

 SqlCommand cmd = new SqlCommand("getEmployee", conn); cmd.AddWithValue('@username', name); cmd.AddWithValue('@password', pass); SqlAdapter da = new SqlAdapter(cmd); DataSet ds= new DataSet(); da.Fill(ds); if (ds.Table.Count > 0 && ds.Table.Rows.Count == 1) { // success } else { // fail } 
  IF(@Count>0) BEGIN SELECT @RetVal = 6 , @ErrMsg = 'A description with the same name exists. Please provide a unique name.' GOTO ERROR END 

在catch中使用内置的StoredProcException,这意味着:

  catch (StoredProcException spEx) { switch (spEx.ReturnValue) { case 6: UserMessageException umEx= new UserMessageException(spEx.Message); throw umEx; } } 

您可以将消息作为字符串而不是spEx.Message传递