How to catch exception when creating MongoClient instance

后端 未结 4 2056
不知归路
不知归路 2020-12-21 07:35

I am using Mongo DB java driver to connect to mongo instance. Below is the code I am using to create the MongoClient instance.

try {
            new MongoCl         


        
4条回答
  •  余生分开走
    2020-12-21 08:20

    It's pretty simple and elegant:

    1. Redirect System.err to a file:

      ByteArrayOutputStream file=new ByteArrayOutputStream();
      System.setErr(new PrintStream(file));
      
    2. Connect to the server with your MongoClient and your MongoCredentials:

      MongoCredential credenciales=MongoCredential.createCredential("root", "admin", "root".toCharArray());
      MongoClient client = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credenciales));
      
    3. Read the error output, which is in the ByteArrayOutputStream object:

      String texto=new String(file.toByteArray());
      
    4. Check whether the Autentication failed string is present:

      if (texto.contains("'Authentication failed.'"))
         // do something;
      else
        ...
      

提交回复
热议问题