mysql canvert mongo_How to properly handle exceptions in MongoClient for VertX

问题

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

}

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=, mechanismProperties={}}

at com.mongodb.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:162)

at com.mongodb.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:39)

... many lines

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

回答1:

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

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

}

});

回答2:

The exception is happening in the mongodb's java driver daemon thread so you cannot catch it.

Vertx MongoClient abstracts you from direct interaction with MongoDB Java driver so you can't modify anything related to the client.

You could access mongo client instance via reflection, but as it's already created you cannot pass additional configuration to it.

If you used com.mongodb.async.client.MongoClient you could pass ServerListener which could access the exception and you could examine it (please see this answer for more details - https://stackoverflow.com/a/46526000/1126831).

But it's only possible to specify the ServerListener in the moment of construction of the mongo client, which happens inside the Vertx MongoClient wrapper and there's no way to pass this additional configuration.

来源:https://stackoverflow.com/questions/55187308/how-to-properly-handle-exceptions-in-mongoclient-for-vertx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值