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

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

本文介绍了从C#存储过程中捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做登陆时验证用户的存储过程。如果成功则返回用户实体,并且工作好!我的问题是,如果它不工作,我会养在SP的错误,我该如何抓住这个错误,并把它用在最好的方法是什么?现在我越来越nullrefference,这是code:存储过程:

I have a stored procedure that is called to validate a user during login.If success it returns the user entity, and that works good! My question is if it doesn't work, I'll raise an error in the SP, How do I catch this error and use it in the best way? Right now I'm getting nullrefference, this is the code:Store procedure:

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

而在code,它看起来像这样,SP是getEmployee的

And in the code it looks like this, the SP is 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;
            }

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

My question is how I should handle the exception?

推荐答案

我一般不会从SP产生一个错误,除非它实际上与操作的系统问题。输入错误的用户名和密码是用户的问题,一个只需要处理在接口级别,所以我会扔大多数的SP路程,处理两个用例(1行或0行返回)在业务层或接口code。如果0行,抛出了错误的用户名或密码消息给客户端,如果1,登录。

I wouldn't generally raise an error from a SP unless it was actually a system problem with the operation. Entering the wrong username and password is a user problem, and one you need only deal with at the interface level, so I'd throw most of that SP away and deal with the two use cases (1 row or 0 rows returned) in the business layer or interface code. If 0 rows, throw up the "Wrong username or password" message to the client and if 1, log in.

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

这篇关于从C#存储过程中捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:14