samedi 18 avril 2015

Spring 4.1.5 MVC ErrorHandler always catches ClassCastException when using MyBatis

I'm using Spring 4.1.5 and MyBatis 3.2.8. Below is a simple representation of the code I have. A controller has a reference to a service, which has a reference to a DAO, which uses MyBatis to query the database.


All of this works great except whenever there is an exception, the front-end always gets a variant of java.lang.ClassCastException:org.springframework.jdbc.UncategorizedSQLException cannot be cast to java.util.List.


MyController.java



@RequestMapping(value = "/list}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<List<String>> getCodes() {
List<String> response = myService.getCodes();
return new ResponseEntity(response, HttpStatus.OK);
}


MyService.java



public List<String> getCodes() {
return myDao.getCodes();
}


MyDao.java (extends SqlSessionDaoSupport)



public List<String> getCodes() {
return getSqlSession().selectList("Codes.selectCodes");
}


So an UncategorizedSQLException is getting thrown because of a malformed query (sometimes it's a BadSQLGrammarException, etc). Jackson attempts to serialize the exception to the expected ResponseBody of List<String>. This can't be done, so a ClassCastException gets thrown instead.


I want to capture the underlying exception and return that to the front-end. I thought that implementing an exception handler in the controller would do the trick, so I modified MyController.java to include the following exception handler.



@ExceptionHandler(UncategorizedSQLException.class)
public @ResponseBody ResponseEntity<String> handleUncategorizedSQLException(UncategorizedSQLException se, HttpServletRequest request, HttpServletResponse response) {

return new ResponseEntity<String>(se.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
}


Unfortunately, this never gets called. If I setup an exception handler for ClassCastException, then I do get into the exception handler, but what I want is to catch the exception before Jackson ever starts trying to serialize the response body.


I'm sure this is possible, and I'm just missing some configuration step. Any idea what I'm missing? Your help is greatly appreciated!! Thanks.


Aucun commentaire:

Enregistrer un commentaire