【问题标题】:Java - How to setup validation with different error messagesJava - 如何使用不同的错误消息设置验证
【发布时间】:2014-02-15 23:45:14
【问题描述】:

我有一个 FileUtils 类,我想调用它来进行一些验证,如果它是错误的,它需要返回一个很好的错误消息,说明验证失败的原因。所以我有:

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());
    }
}

但这对我来说似乎很奇怪,因为 isValidFile 调用永远不会是假的。此外,如果我颠倒 if 条件的顺序以快速启动代码,如果它是错误的,它看起来就更奇怪了。另外,我不喜欢将异常处理代码作为传递错误消息的一种方式。

public void anotherMethod()
{
    try
    {
        if(!isValidFile(file))
            return;
        doSomething();
        ..
        doMoreThings();
    } catch (Exception e) {
        displayErrorMessage(e.getMessage());
    }
}

有没有办法在不使用异常的情况下完成所有这些操作,并且仍然能够让 isValidFile() 方法返回错误的指示,而无需返回带有错误代码的 int,就像在 C 等中看到的那样。

【问题讨论】:

    标签: java exception error-code


    【解决方案1】:

    你可以例如将您的方法更改为

    public static List<String> isValidFile(File file)

    当文件有效时返回一个空列表或null
    否则返回一个包含验证问题的列表。
    返回值是您验证是否失败的指示。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      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);
          }
      }
      

      不是很漂亮,但它可以完成工作。

      【讨论】:

        猜你喜欢
        • 2012-10-11
        • 2018-07-11
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-16
        • 1970-01-01
        • 2023-03-18
        相关资源
        最近更新 更多