tags:

views:

23

answers:

2

Hello

Lets say I have something like this:

public ActionResult Test(SomeModel m)
{

    try
    {
        _db.SaveModel(m);

        SendMailToUser(m);
        RedirectToRoute("Something");
    }
    catch
    {
        return View();
    }

}

And I got problems with howto deal with this if "SendMailToUser" fails. Model gets saved to database. How can I make it continue if the mail fails to send?

/M

+1  A: 
public ActionResult Test(SomeModel m)
{

    try
    {
        _db.SaveModel(m);
        try
        {
            SendMailToUser(m);
        }
        catch
        {
            //do something
        }
        RedirectToRoute("Something");
    }
    catch
    {
        return View();
    }

}
gandjustas
+1  A: 

If you just want to swallow the exception (if thrown) from the SendMailTouser(m) function you could do:

public ActionResult Test(SomeModel m)
{
    try
    {
        _db.SaveModel(m);
    }
    catch
    {
        return View();
    }

    try
    {
        SendMailToUser(m);
    }
    catch { }
    finally
    {
        RedirectToRoute("Something");
    }
}

If you want to not save the model if the email sending fails, you should wrap the two in a unit-of-work or a transaction block such that it will rollback the Save if the email fails.

Michael Shimmins