问题描述
我想知道,如果用户违反某些业务规则,是否推荐使用 ApplicationException
返回应用程序错误。例如:
I'd like to know if the use of ApplicationException
is recommended to return application errors when a user breaks some business rule. For example:
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");
}
这是一个好还是坏的策略?如果不是,那么会是更好的方法?
Is it a good or bad strategy? If isn't, what would be a better approach?
推荐答案
在你的代码示例中,你会更好地投掷一个 ArgumentNullException
它更有意义。 ApplicationException
并没有真正给调用者任何关于异常的含义的指示。
In your code example, you would be better off throwing an ArgumentNullException
it is more meaningful. ApplicationException
does not really give the caller any indication as to what the exception means.
至于最后一次检查有效的电子邮件( ArgumentException
或继承自参数
异常的自定义异常类将是最好的。
As for the last check for the valid email, either an ArgumentException
or a custom exception class that inherits from Argument
exception would be best.
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
}
这篇关于使用ApplicationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!