【问题标题】:proceed with the code when user is authenticated successfully成功验证用户身份后继续执行代码
【发布时间】:2018-05-21 12:10:35
【问题描述】:

我正在用 Java 和 jGit 创建一个应用程序(继续how to authorize an user using jGit)。目前我能够隔离异常,如果用户提供无效凭据,我会得到not authorized,如果用户无权访问声明的 repo,我会得到repository not found。现在我的问题是,用户正在通过身份验证,因为用户无权访问存储库,因此引发了第二个异常。但是在这里我想在另一个类中处理它,即我希望这个类只处理用户的身份验证。下面是我的代码

import java.io.File;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class AuthenticateanUser {

    public static void main(String[] args) throws Exception {
        final String REMOTE_URL = "https://myRepo.git";
        // prepare a new folder for the cloned repository
        File localPath = File.createTempFile("TestGitRepository", "");
        localPath.delete();
        // then clone
        try (Git result = Git.cloneRepository().setURI(REMOTE_URL)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider("myId", "myPwd"))
                .setDirectory(localPath).call()) {

            System.out.println("Having repository: " + result.status());
        } catch (Exception e) {
        if (e.getMessage().toLowerCase().contains("repository not found"))
            System.out.println("Exception Repo not found");
        else if (e.getMessage().toLowerCase().contains("not authorized"))
            System.out.println("Exception Invalid Credentials");
        else
            System.out.println(e);

    }
    }

}

请让我知道我哪里出错了,我该如何解决这个问题。

谢谢

【问题讨论】:

    标签: java exception-handling jgit


    【解决方案1】:

    您应该链接异常,而不是使用顶级异常类。克隆时抛出GitAPIException。您可以尝试先捕获可能的情况,然后让主要的异常处理休息。

    public static <R>R handleClone(String uri,File local,boolean bare,Function<Git,R> fn){
      try {
        Git g=Git.cloneRepository().setURI(uri).setBare(bare).setDirectory(local).call();
        return handle(g,fn);
      }
     catch (  GitAPIException e) {
        throw new IllegalStateException(e);
      }
    }
    

    异常链接示例:

    catch (  IOException e) {
        return new Status(IStatus.ERROR,GitActivator.PI_GIT,"Error cloning git repository",e);
      }
    catch (  CoreException e) {
        return e.getStatus();
      }
    catch (  GitAPIException e) {
        return getGitAPIExceptionStatus(e,"Error cloning git repository");
      }
    catch (  JGitInternalException e) {
        return getJGitInternalExceptionStatus(e,"Error cloning git repository");
      }
    catch (  Exception e) {
        return new Status(IStatus.ERROR,GitActivator.PI_GIT,"Error cloning git repository",e);
      }
      return Status.OK_STATUS;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 2019-11-08
      • 2016-12-06
      • 2021-09-09
      相关资源
      最近更新 更多