如何处理Spring数据中的DuplicateKeyException mongodb

时间:2017-09-28 09:06:09

标签: java spring-mvc

插入数据的方法

    public  String home()  {

    try
    {
    MongoData data=new MongoData();
    data.setDate(new Date());
    data.setName("frji");

    //mongoTemplate.insert(data);
    mongoTemplate.save(data);
    }
    catch (DuplicateKeyException e) {

    }
    catch (MongoException e) {

    }
    return "home";
}

实体类

  @Document(collection="integer_test")
public class MongoData {
    @Id
    private String id;
    private Date date;
    @Indexed(unique=true)
    private String name;
    @Override
    public String toString() {
        return "MongoData [date=" + date + ", id=" + id + "]";
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

但它没有捕获异常。它将显示在用户界面上。然后我如何在java端捕获此异常。

  

com.mongodb.MongoException $ DuplicateKey:{" serverUsed" :   " 192.168.1.113:27017" ," ok" :1," n" :0,"错误" :" E11000重复   密钥错误索引:jmailer_digiengage.integer_test。$ name dup key:{:   \" frji \" }" ,"代码" :11000}在   com.mongodb.CommandResult.getWriteException(CommandResult.java:88)at   com.mongodb.CommandResult.getException(CommandResult.java:79)at   com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:415)     在com.mongodb.DBCollectionImpl.insertImpl(DBCollectionImpl.java:210)     在com.mongodb.DBCollection.insert(DBCollection.java:176)at   com.mongodb.DBCollection.insert(DBCollection.java:161)at   com.mongodb.DBCollection.insert(DBCollection.java:107)at   com.mongodb.DBCollection.save(DBCollection.java:1214)at   com.mongodb.DBCollection.save(DBCollection.java:1179)at   org.springframework.data.mongodb.core.MongoTemplate $ 11.doInCollection(MongoTemplate.java:1106)     在   org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:479)     在   org.springframework.data.mongodb.core.MongoTemplate.saveDBObject(MongoTemplate.java:1101)     在   org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1034)     在   org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:981)     在   org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:969)     在com.mongo.test.HomeController.home(HomeController.java:62)at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)at   org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)     在   org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)     在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)     在   org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)     在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)     在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)     在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)     在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:635)at   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:742)at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)     在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)     在   org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)     在   org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)     在   org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:798)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1441)     在   org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)     在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:745)

3 个答案:

答案 0 :(得分:2)

您可以创建 HandlerExceptionResolver 来处理并向UI显示用户友好的消息。

How to create HandlerExceptionResolver

更新:如果您只想处理异常,请在catch块中编写org.springframework.dao.DuplicateKeyException

try{
  //TODO
} catch(org.springframework.dao.DuplicateKeyException e){
 //TODO - Do want you want
}

答案 1 :(得分:0)

你怎么知道它没有发现异常?您的异常处理代码没有做任何事情!

当发生重复异常时,您需要添加一些有意义的实际操作

public  String home()  {
  try {
    MongoData data=new MongoData();
    data.setDate(new Date());
    data.setName("frji");
    mongoTemplate.save(data);
  } catch (DuplicateKeyException | MongoException e) {
    //Exception handling
    return "an error occurred: " + e.getMessage();
  }
  return "home";
} 

或者删除异常处理,并抛出异常。

public  String home()  {
  MongoData data=new MongoData();
  data.setDate(new Date());
  data.setName("frji");
  mongoTemplate.save(data);
  return "home";
} 

答案 2 :(得分:0)

回答很晚,但可能对某人有所帮助。 在这里扩展 Mehraj Malik 的回答,

另一种方法是捕获异常并在内部检查它是否是 Duplicate 或任何其他异常。通过这种方式,我们也可以检查任何其他异常:

导入 org.springframework.dao.DuplicateKeyException;

try {
// 
} catch(Exception ex) {
 log.info("Exception occurred: ", ex); //to log exception
  if(ex instanceof DuplicateKeyException) {
      // duplicate key exception exists
  } else {
  // do something else
  }

}