我可以使用多个try catch块来抛出多个错误或异常

时间:2018-03-24 13:08:03

标签: java maven api bitbucket jgit

下面的代码是git push命令通过java的所有内容如果我在没有使用try catch块的情况下运行它成功推送文件,但是如果用户输入错误的URL和用户名和密码,请使用try和catch来获取错误阻止任何人都可以在代码中正确编辑它。

  public void pushRepo (String repoUrl, String gitdirectory, String username, String password) throws GitAPIException
{

      Git git = null;
    try {
        git = Git.open(new File(gitdirectory));
    } catch (IOException e1) {
        System.out.println("it is not git directory");
    }
      RemoteAddCommand remoteAddCommand = git.remoteAdd();
      remoteAddCommand.setName("origin");
      try {
      remoteAddCommand.setUri(new URIish(repoUrl));
      System.out.println("file added");
      }catch (Exception e) {
           System.out.println("Invalid RemoteUrl");
        }
      remoteAddCommand.call();
      git.add().addFilepattern(".").call();
      git.commit().setMessage("commited").call();
      PushCommand pushCommand = git.push();
      try {
      pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
      pushCommand.setRemote("origin").add("master").call();
      System.out.println("push file");
      }catch(Exception e)
      {
          System.out.println("Invalid username and password");
      }

    }
}

如果我输入任何网址,用户名和密码的值不正确,则会始终显示“用户名和密码无效”等消息。

1 个答案:

答案 0 :(得分:4)

尝试制作自定义验证器

public class ValidationErrorException extends Exception {

private List<String> errors;

public ValidationErrorException(List<String> errors) {
    super("Validation Errors.");
    setErrors(errors);
}

public ValidationErrorException(String message, List<String> errors) {
    super(message);
    setErrors(errors);
}

public void setErrors(List<String> errors) {
    this.errors = errors;
}

public List<String> getErrors() {
    return errors;
  }
 }

添加你的功能。

  

抛出ValidationErrorException

然后使用

try {
        // write code for check url
    } catch (Exception ex) {
        List<String> errors = new ArrayList<>();
        errors.add("Invalid URL...");
        throw new ValidationErrorException(errors);
    }

等等用户名和密码。