开发者

Is the MVC Controller Layer the ideal place for error handling?

开发者 https://www.devze.com 2023-01-10 13:15 出处:网络
It would seem so to me, because nearly all exceptions thrown downstream of whatever routes requests to controllers, will be thrown in a controller or something downstream from a controller.There is no

It would seem so to me, because nearly all exceptions thrown downstream of whatever routes requests to controllers, will be thrown in a controller or something downstream from a controller. There is nothing upstream from a controller except a view, which is simply开发者_高级运维 a presentation of what happened in the controller.


Controller actions are an ideal place for most of the error handling but not all of it.

The view isn't rendered until after your controller action finishes executing. So if for example you pass the view a viewmodel that is more than a simple data container and it throws an exception while the view is being rendered (not an uncommon scenario). You can't catch this in your controller action.

Here's a tool you can use to catch exceptions outside the controller http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx


It's usually determined by the Controller which View you need to display so errors which occur at lower levels e.g. BLL/DAL, can still do error handling and can just be aided by the controller e.g.

public ActionResult DisplayObject(int id)
{
    // high level error handling
    using (MyRepo repo = new MyRepo()) 
    {
        var obj = repo.GetObj(id);
        if (obj == null)
            return View("ErrorDisplayingObject");
        else
            return View("ObjectDetails");
    }
}
...

public ActionResult SaveObject(int id, string param1, string param2)
{
    // high level error handling
    using (MyRepo repo = new MyRepo()) 
    {
        var obj = repo.GetObj(id);
        if (obj != null)
        {
            obj1.Param1 = param1;
            obj2.Param2 = param2;
            if (repo.Save())
                return View("SaveConfirmation");
        }          
    }
    return View("ErrorSavingObject");
}

...
public class MyRepo
{
    public MyObject GetObj(int id)
    {
        // low level error handling
        try
        {
            // retrieve object

        }
        catch (Exception)
        {
             return null;
        }
    }

    public bool Save()
    {
        // low level error handling
        try
        {
            // save data
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}


Model has to be the most appropriate place where u can do the validation. Ideally model has to be the place where domain model should be place.. So, that makes it an ideal place to do error validation


It depends on the exception and what your action does. For example, if you´re saving an entity that could possibly be breaking some business rules, then it is expected that your BLL throws an exception (e.g. BusinessRuleXXException) to signal this non-compliance situation. In this case, you have to handle that exception (the Controller is a good place for doing this) and show the user an appropriate message indicating what is wrong (You can not save this because of bla bla...).

On the other hand, you may have a buggy application in wich you´re performing some action and you provoke an error, like for example a PK constraint being violated or maybe an external service is unavailable or any other situations that are not expected an represent real exceptions in your application. For this kind of errors, my suggestion is to handle them globally by using either a HandleError filter or a custom filter that handles errors and logs them, and redirect the user to an error page where a friendly "Sorry, something went wrong. A team of highly trained monkeys has been dispatched to deal with this situation" message is shown.

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消