如何在MongoClient for VertX中正确处理异常 [英] How to properly handle exceptions in MongoClient for VertX

查看:738
本文介绍了如何在MongoClient for VertX中正确处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的启动方法中,我要检查提供给应用程序的MongoDB凭据是否正常.如果一切正常,我将继续启动,否则,应用程序将退出,因为它无法连接至数据库.代码段如下:

In the startup method of my application I want to check that the credentials for MongoDB provided to the application are OK. If they are OK, I continue the startup, if not, the application is supposed to exit as it cannot connect to the DB. The code snippet is as below:

  // Create the client
  MongoClient mongodb = null;
  try {
      mongodb = MongoClient.createShared(vertx, mongo_cnf, mongo_cnf.getString("pool_name"));
  }
  catch(Exception e) {
      log.error("Unable to create MongoDB client. Cause: '{}'. Bailing out", e.getMessage());
      System.exit(-1);
  }

如果我提供了错误的凭据,则不会调用catch块.但是我在控制台上得到了以下内容:

If I provide wrong credentials, the catch block is not called. Yet I get the following on the console:

  19:35:43.017 WARN  org.mongodb.driver.connection - Exception thrown during connection pool background maintenance task
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='user', source='admin', password=<hidden>, mechanismProperties={}}
    at com.mongodb.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:162)
    at com.mongodb.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:39)
... many lines

问题是:如何在我的代码中拦截此异常并能够正确处理它?<​​/p>

The question is: how to intercept this exception in my code and be able to handle it properly ?

推荐答案

当前不会引发异常,我认为这是设计上的错误,因为您收到了无法使用的对象.随时打开错误: https://github.com/vert-x3/vertx-mongo-client/issues

Currently the exception is not thrown, which in my opinion a mistake in design, since you receive an object that you cannot work with. Feel free to open a bug: https://github.com/vert-x3/vertx-mongo-client/issues

您可以检测20个重试尝试来检测客户端是死机还是到达":

What you can do to detect that your client is "dead or arrival" is to wait for 20 retry attempts:

MongoClient client = MongoClient.createShared(vertx, config, "pool_name");
client.findOne("some_collection", json1, json2, (h) -> {
    if (h.succeeded()) {
        //...
    }
    else {
        // Notify that the client is dead
    }
});

这篇关于如何在MongoClient for VertX中正确处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆