如何处理MVC3中的异常?

时间:2012-08-09 15:29:12

标签: asp.net-mvc-3 exception-handling error-handling

我在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之后,我只是调用帮助程序类,即AccountServiceHelper来使用CreatePerson之类的Web服务方法。

My 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 { }
}

我的问题是如何在helper类中处理Exception并返回控制器。

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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
    }
}

如果您的助手类中发生异常,并且您没有在助手类中专门捕获它,那么无论如何它都会冒泡到您的控制器。因此,如果您不想在助手类中处理它,则无需捕获它,因为它最终会在您的控制器中结束。

答案 2 :(得分:0)

从你的帮助类中抛出它