[英]Java - How to setup validation with different error messages
I have a FileUtils class that I would like to call that does some validation, and if it's wrong, it needs to return a good error message as to why the validation failed. 我有一个FileUtils类,我想调用它进行一些验证,如果不正确,它需要返回一个很好的错误消息,说明验证失败的原因。 So I have:
所以我有:
public static boolean isValidFile(File file) throws Exception
{
if(something)
throw new Exception("Something is wrong");
if(somethingElse)
throw new Exception("Something else is wrong");
if(whatever)
throw new Exception("Whatever is wrong");
return true;
}
public void anotherMethod()
{
try
{
if(isValidFile(file))
doSomething();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
But this just seems odd to me because the isValidFile call can never be false. 但这对我来说似乎很奇怪,因为isValidFile调用永远不能为假。 Also if I reverse the order of the if condition to do a quick boot out of the code if it's false, it's even weirder looking.
另外,如果我颠倒了if条件的顺序以在错误的情况下从代码中快速启动,那看起来甚至很奇怪。 Plus I don't like having exception handling code as a way of passing an error message.
另外,我不喜欢将异常处理代码作为传递错误消息的方式。
public void anotherMethod()
{
try
{
if(!isValidFile(file))
return;
doSomething();
..
doMoreThings();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
Is there a way to do all this without using Exceptions to and still be able to have the isValidFile() method return an indication of what the error is without returning an int with an error code like you see in C, etc. 有没有办法在不使用Exception的情况下完成所有这些工作,并且仍然能够使isValidFile()方法返回错误的指示,而无需返回带有C中所见错误代码的int等。
You can eg change your method to 您可以例如将方法更改为
public static List<String> isValidFile(File file)
When the file is valid return an empty list or null
, 当文件有效时,返回一个空列表或
null
,
otherwise return a list with the validation problems. 否则,返回包含验证问题的列表。 The
该
return value is your indication if validation failed or not. 返回值是验证是否失败的指示。
You could do something like this: 您可以执行以下操作:
public static String validateFile(File file)
{
String ret = null;
if(something) {
ret = "Something is wrong";
} else if(somethingElse) {
ret = "Something else is wrong";
} else if(whatever) {
ret ="Whatever is wrong";
}
return ret;
}
public void anotherMethod()
{
String errorMessage = validateFile(file);
boolean fileIsValid = errorMessage == null;
if (fileIsValid) {
doSomething();
} else {
displayErrorMessage(errorMessage);
}
}
Not really pretty, but it gets the job done. 不是很漂亮,但是可以完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.