How to capture mongodb exceptions in java?

1

Hi, I have the following code in which I connect to the database, but I can not capture the exceptions that the mongo driver presents in any way.

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.MongoSocketOpenException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 *
 * @author personal
 */
public class mongodb {

    private MongoClient mongoClient;
    private MongoDatabase database;
    private MongoCollection<Document> collection;

    public mongodb() {

        try {
            mongoClient = new MongoClient("localhost", 27017);
            database = mongoClient.getDatabase("ferreteria");

        } catch (MongoSocketOpenException e) {
            System.out.println("Error al conectarse con la base de datos");
        }
    }

    public MongoCollection<Document> getCollection(String tabla) {

        try {
            return collection = database.getCollection(tabla);
        } catch (MongoException e) {
            return null;
        }

    }

    public static void main(String[] args) {
        mongodb conexion = new mongodb();

       MongoCollection<Document> productos = conexion.getCollection("productos");
//        Document doc = new Document("name", "MongoDB")
//                .append("type", "database")
//                .append("count", 1)
//                .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
//                .append("info", new Document("x", 203).append("y", 102));
//        productos.insertOne(doc);
//        List<Document> documents = new ArrayList<>();
//        for (int i = 0; i < 100; i++) {
//            documents.add(new Document("i", i));
//        }
//        productos.insertMany(documents);
    }

}
    
asked by Sergio Guerrero 11.01.2017 в 00:57
source

1 answer

0

You're catching MongoDB's own exceptions, such as MongoSocketOpenException and MongoException :

try {
            mongoClient = new MongoClient("localhost", 27017);
            database = mongoClient.getDatabase("ferreteria");

        } catch (MongoSocketOpenException e) {
            System.out.println("Error al conectarse con la base de datos");
        } catch (MongoException e) {
            return null;
        }

Probably other types of exceptions are being generated, you can add:

  } catch(Exception e) {
    System.out.println("Error "+ e.getMessage();
    }
    
answered by 11.01.2017 в 03:27