在MVC中,管理业务中的异常或错误的最佳方法是什么?

Bas*_*mme 6 .net c# asp.net-mvc exception-handling

在MVC中,管理业务中的异常或错误的最佳方法是什么?我找到了几个解决方案但不知道选择哪个.

解决方案1

public Person GetPersonById(string id)
{
    MyProject.Model.Person person = null;
    try
    {
        person = _personDataProvider.GetPersonById(id);
    }
    catch 
    { 
        // I use a try / catch to handle the exception and I return a null value
        // I don't like this solution but the idea is to handle excpetion in 
        // business to always return valid object to my MVC.
        person = null; 
    }
    return person;
}
Run Code Online (Sandbox Code Playgroud)

解决方案2

public Person GetPersonById(string id)
{
    MyProject.Model.Person person = null;
    person = _personDataProvider.GetPersonById(id);
    // I do nothing. It to my MVC to handle exceptions
    return person;
}
Run Code Online (Sandbox Code Playgroud)

解决方案3

public Person GetPersonById(string id, ref MyProject.Technical.Errors errors)
{
    MyProject.Model.Person person = null;
    try
    {
        person = _personDataProvider.GetPersonById(id);
    }
    catch (Exception ex)
    { 
        // I use a try / catch to handle the exception but I return a 
        // collection of errors (or status). this solution allow me to return 
        // several exception in case of form validation.
        person = null; 
        errors.Add(ex); 
    }
    return person;
}
Run Code Online (Sandbox Code Playgroud)

解决方案4

// A better idea ?
Run Code Online (Sandbox Code Playgroud)

Hus*_*vic 1

我还建议您考虑空对象模式。不要返回 null,而是返回一个空对象,这样您就不必执行多次 if null 检查。您应该创建一个抽象 Person 类,该类具有静态属性,例如包含默认值的 NullPerson。如果您的 DAL 返回 null,您将返回 NullPerson。您可以找到有关空对象模式的更多信息。