0

我在 MVC3 应用程序中工作。我很难在我的控制器中处理异常。

我的帐户控制器在这里,

public ActionResult Register(NewRegister model)
{
    if (ModelState.IsValid)
    {
        if (!IsUserLoginExist(model.Email))
        {
            AccountServiceHelper.CreatePerson(model);
            return RedirectToAction("RegistrationConfirmation", "Account");
        }
        else
        {
            ModelState.AddModelError("","Email Address already taken.");
        }
    }
    return View(model);
}

验证后,IsUserLoginExist我只是调用 Helper 类,即AccountServiceHelper使用 Web 服务方法,如CreatePerson.

我的 Helper 类如下所示:

public static void CreatePerson(NewRegister model)
{
    try
    {
        try
        {
            var FirstName = model.FristName;
            var LastName = model.LastName;
            var Email = model.Email;
            var Role = model.Role;
            var Password = model.Password;
            .....
            .....
            service.CreatePerson(model);
            service.close();
        }
        catch(Exception e) 
        {

        }
    }
    catch { }
}

我的问题是如何处理助手类中的异常并返回控制器。

4

3 回答 3

1

一种可能性是在您的控制器处处理异常:

public static void CreatePerson(NewRegister model)
{
    var FirstName = model.FristName;
    var LastName = model.LastName;
    var Email = model.Email;
    var Role = model.Role;
    var Password = model.Password;
    .....
    .....
    service.CreatePerson(model);
    service.close();
}

进而:

public ActionResult Register(NewRegister model)
{
    if (ModelState.IsValid)
    {
        try
        {
            if (!IsUserLoginExist(model.Email))
            {
                AccountServiceHelper.CreatePerson(model);
                return RedirectToAction("RegistrationConfirmation", "Account");
            }
            else
            {
                ModelState.AddModelError("", "Email Address already taken.");
            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
        }
    }
    return View(model);
}
于 2012-08-09T15:34:07.633 回答
1

就像其他人说的那样,你使用这个方法从你的助手类中抛出它:

public static void CreatePerson(NewRegister model)
{
    try
    {
        var FirstName = model.FristName;
        var LastName = model.LastName;
        var Email = model.Email;
        var Role = model.Role;
        var Password = model.Password;
        .....
        .....
        service.CreatePerson(model);
        service.close();
    }
    catch(Exception e) 
    {
        // handle it here if you want to i.e. log

        throw e; // bubble it to your controller
    }
}

If an exception occurs in your helper class, and you don't specifically catch it in your helper class, it will bubble up to your controller anyway. So if you don't want to handle it in your helper class, there's no need to catch it as it will end up in your controller anyway.

于 2012-08-09T15:45:58.567 回答
0

从你的助手类中扔掉它

于 2012-08-09T15:35:21.917 回答