c# - ApplicationException的使用

标签 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"); 
}

这是好策略还是坏策略?如果不是,什么是更好的方法?

最佳答案

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

You should derive custom exceptions from the Exception class rather than the ApplicationException class. You should not throw an ApplicationException exception in your code, and you should not catch an ApplicationException exception unless you intend to re-throw the original exception.

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

关于c# - ApplicationException的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854311/

相关文章:

asp.net-mvc - ASP.NET MVC 编辑集合最佳实践 - 您的意见

asp.net - 使用 LDAP 时无法与服务器建立安全连接

C# - Int 操作莫名其妙地返回负值

c# - 如何使用 Css 文件更改按钮文本颜色 onclick 事件(asp.net、C#)?

asp.net - 在 MySQL 中使用 INNER JOIN 和 SqlDataSource 时出现语法错误

asp.net - 阻止 AJAX 计时器控制请求扩展 FormsAuthentication 票证?

asp.net-mvc - ASP.NET 不向客户端发送上传进度

c# - 从表达式中获取负数

c# - 通用输出目录、Web 应用程序和 IIS Express

c# - C# 中的泛型和访问 T 的静态成员