MongoWriteException не перехватывается Java try catch block - MongoDB Server 4.2 - Java Driver 3.12.0 - Проблема с исключениями MongoDB - PullRequest
0 голосов
/ 20 апреля 2020

У меня есть следующий блок кода, который имеет обработчик исключений для MongoException. Но хотя здесь INSERT вызывает исключение MongoWriteException, элемент управления никогда не переходит в блок try catch. Трассировка стека печатается несмотря на комментируемый код. Также попытался использовать MongoException и DuplicateKeyException вместо безрезультатно.

protected boolean performDatabaseInsert(Document generic_document,String document_type) // document type is employee,department or leaveTransaction 
    {
        try
        {       
            generic_collection = mdb.getCollection(document_type);
            generic_collection.insertOne(generic_document);
            return true;

        }catch (MongoWriteException me) 
        {
            System.out.println("Exception occured on SignUp !");
            //me.printStackTrace();
            exception_handler.handleException(me);
            return false;
        }
     }

Следующая операция StackTrace выводится на консоль после операции INSERT.

com.mongodb.MongoWriteException: E11000 duplicate key error collection: LeaveApplicationSystemDB.employees index: username_1_is_admin_1 dup key: { username: "ali", is_admin: true }
    at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1060)
    at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:503)
    at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:487)
    at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:481)
    at leaveapplicationsystem.MongoDatabaseConnectionImpl.performDatabaseInsert(MongoDatabaseConnectionImpl.java:59)
    at leaveapplicationsystem.lasServicesMongoImpl.performSignUpAction(lasServicesMongoImpl.java:72)
    at leaveapplicationsystem.SignUpServlet.doPost(SignUpServlet.java:69)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:830)


protected boolean handleException(MongoException s)
    {
        int error_code = s.getCode();
        String error_message = s.getMessage();
        System.out.println("App Action : " + InformationState.app_action);
        System.out.println("Error Code : " + error_code + "--" + error_message);

        switch (InformationState.app_action)
        {
            case "SignUp" :  //handle all possible SQL exceptions on SignUp. 
            {
                switch (error_code)
                {
                    case 11000 : //Integrity constraint violated, username already in use. 

                            System.out.println("Unique constraint violation...");
                            notify_appstate.setErrorMessage("Username/Employee# specified is already in use. Try again !. ");
                    break;

                    default:
                            notify_appstate.setErrorMessage("Unknown Error occurred. Contact System Admin. !");
                    break;
                }
            }
            break;
...