使用ApplicationException

Fab*_*elz 2 c# asp.net asp.net-mvc design-patterns

我想知道ApplicationException当用户违反某些业务规则时,是否建议使用它来返回应用程序错误.例如:

public void validate(string name, string email)
{   
    int count1 = (from p in context.clients
        where (p.name == clients.name)
        select p).Count();

    if (count1 > 0)
        throw new ApplicationException("Your name already exist in the database");

    int count2 = (from p in context.clients
        where (p.email == clients.email)
        select p).Count();

    if (count2 > 0)
        throw new ApplicationException("Your e-mail already exist in the database"); 
}
Run Code Online (Sandbox Code Playgroud)

这是一个好的或坏的策略?如果不是,那会是更好的方法?

Ric*_*eal 8

在你的代码示例中,你最好抛弃ArgumentNullException它更有意义.ApplicationException并没有真正给调用者任何关于异常意味着什么的指示.

至于有效电子邮件的最后一次检查,ArgumentExceptionArgument异常继承的自定义异常类最好.

 public void update(string name, string email)
    {
        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentNullException(nameof(name), "Type your name");
        }

        if (string.IsNullOrEmpty(email))
        {
            throw new ArgumentNullException(nameof(email), "Type your e-mail");
        }

        if (isValidEmail(email))
        {
            throw new ArgumentException(nameof(name), "Invalid e-mail");
        }

        //Save in the database
    }
Run Code Online (Sandbox Code Playgroud)


Jak*_*rtz 6

来自https://msdn.microsoft.com/en-us/library/System.ApplicationException:

您应该从Exception类而不是ApplicationException类派生自定义异常.您不应该在代码中抛出ApplicationException异常,除非您打算重新抛出原始异常,否则不应捕获ApplicationException异常.

一个简单的原因是.NET中有其他异常类派生自ApplicationException.如果在代码中抛出ApplicationException并在以后捕获它,您可能还会捕获可能会破坏应用程序的派生异常.