title: how to get error messages from mongoRepository.save()
body: <p>I'm using mongoRepository.save() but cannot get error information for when duplicates prevent insertion.
  As a test I'm inserting a duplicate username and mongo simply ignores it. but when username is unique it is inserted as expected.</p>
  
  <p>See below for my service class:</p>
  
  <pre><code>package com.onlinedateshow.service;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.data.mongodb.core.MongoTemplate;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  import org.springframework.stereotype.Service;
  
  import com.mongodb.BasicDBObject;
  import com.onlinedateshow.data.model.User;
  import com.onlinedateshow.data.repo.user.UserRepository;
  import com.onlinedateshow.model.ui.RegisterUI;
  import com.onlinedateshow.model.util.RegisterMapper;
  
  @Service
  public class RegisterService {
      @Autowired
      private UserRepository userRepo;
  
      @Autowired
      MongoTemplate template;
  
      public String addUser(RegisterUI registerData) {
  
          User newUser = RegisterMapper.toPersistenceBean(registerData);
  
          try{
  
              //does not return error, if duplicates are found, silently 
              //ignores the query
              User saveduser = userRepo.save(newUser);
  
  
              //below is what I want but don't know how to get it from a repository
              //String error = template.getDb().getLastError().getErrorMessage();
              //return error;
              return null;
  
  
          }catch(Exception e){
              return e.getLocalizedMessage();
          }
      }
  
  
  }
  </code></pre>
  
  <p>and this is my UserRepository interface:</p>
  
  <pre><code>package com.onlinedateshow.data.repo.user;
  
  
  import org.springframework.data.mongodb.repository.MongoRepository;
  import org.springframework.data.repository.PagingAndSortingRepository;
  
  import com.onlinedateshow.data.model.User;
  
  public interface UserRepository extends MongoRepository&lt;User, String&gt;,
  PagingAndSortingRepository&lt;User, String&gt; {
      User findByEmail(String email);
  
      User findById(String id);
  
      User findByUserName(String userName);
  }
  </code></pre>
  
  <p>And this is my XML file which sets up the MongoDbFactory:</p>
  
  <pre><code>&lt;!-- Activate Spring Data MongoDB repository support --&gt;
      &lt;mongo:repositories base-package="com.mydata.repo.user" /&gt;
  
      &lt;!-- MongoDB host --&gt;
      &lt;mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}" /&gt;
      &lt;mongo:db-factory dbname="${mongo.db.name}" /&gt;
  
      &lt;!-- Template for performing MongoDB operations --&gt;
      &lt;bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"
          c:mongo-ref="mongo" c:databaseName="${mongo.db.name}" /&gt;
  </code></pre>