Refactor similar Spring MVC ExceptionHandlers

Monday, May 5, 2014

I have below exception handlers repeated in couple Spring MVC controllers. I know those can be refactored into a single bean or into WebMvcConfigurerAdapter but I couldn't find any examples. I don't have any views, it's a REST API...


How can I refactor those with java configuration? If possible I'd prefer to refactor those into a custom WebMvcConfigurerAdapter



......
......
@ExceptionHandler({MissingServletRequestParameterException.class,
UnsatisfiedServletRequestParameterException.class,
HttpRequestMethodNotSupportedException.class,
ServletRequestBindingException.class,
TypeMismatchException.class
})
public ResponseEntity<DataCarrier> handleException(Exception exception) {
logger.warn("A bad input received.");
return new ResponseEntity<DataCarrier>(new ErrorDto("Input data is not valid."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({AccountNotFoundException.class, NoAccountException.class})
public ResponseEntity<DataCarrier> noAccountFoundException(Exception exception) {
return new ResponseEntity<DataCarrier>(HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler({HeaderPropertyException.class})
public ResponseEntity<DataCarrier> headerPropertyException(Exception exception) {
logger.error("[{}].", exception.getMessage(), exception);
return new ResponseEntity<DataCarrier>(HttpStatus.INTERNAL_SERVER_ERROR);
}






http://ift.tt/1ifV6sA