0

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?

MEZesUBI
  • 297
  • 7
  • 17

1 Answers1

1

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.

    }
Jahnavi Paliwal
  • 1,721
  • 1
  • 12
  • 20