Spring+Mongo : Handle Connection Timeout

954 Views Asked by At

I am connecting to MongoDB with a Spring application. Basic configurations are in a properties file, I have some Mongo configs there. I have a custom Configuration class for MongoDB options to set the timeout limits.

When I query for multiple entries, I often get Connection Timeout errors as a response.

Question: I would like to be able to handle timeout errors, so I can send a custom message to the client whenever connection reaches timeout. Where/how is it possible?

1

There are 1 best solutions below

0
On BEST ANSWER

You can catch MongoTimeoutException and perform any action within the catch block. PFB an example:

@Test
public void testMongoDBConnect() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(new MongoClientURI(MONGO_URI));
    DB database = mongoClient.getDB(DB_NAME);
    DBCollection collection = database.getCollection(COLLECTION_NAME);
    try {
         //Any operation on Mongo Collection

    } catch (MongoTimeoutException ex) {
        //Perform your action here - Email Alert etc.

    }