Skip to content

Instantly share code, notes, and snippets.

@jasoet
Created November 13, 2012 05:10
Show Gist options
  • Save jasoet/4064028 to your computer and use it in GitHub Desktop.
Save jasoet/4064028 to your computer and use it in GitHub Desktop.
ExceptionHandler
/**
* Deny Prasetyo, S.T.
* jasoet87@gmail.com
* [at] jasoet
* github.com/jasoet
* bitbucket.org/jasoet
*/
public abstract class BaseExceptionHandler extends BaseLogHelper {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({NoResultException.class})
public void handle(NoResultException ex, HttpServletResponse response) {
ex.printStackTrace();
response.setHeader("Exception Message", ex.getMessage());
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({EmptyResultDataAccessException.class})
public void handle(EmptyResultDataAccessException ex, HttpServletResponse response) {
ex.printStackTrace();
response.setHeader("Exception Message", ex.getMessage());
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({IllegalStateException.class})
public void handle(IllegalStateException ex, HttpServletResponse response) {
ex.printStackTrace();
response.setHeader("Exception Message", ex.getMessage());
}
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@ExceptionHandler({MethodArgumentNotValidException.class})
public void handle(MethodArgumentNotValidException ex, HttpServletResponse response) throws IOException {
ex.printStackTrace();
Map<String, String> errorMap = new HashMap<String, String>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errorMap.put(error.getField(), error.getDefaultMessage());
}
response.setHeader("Exception Message", new ObjectMapper().writeValueAsString(errorMap));
}
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@ExceptionHandler({DataIntegrityViolationException.class})
public void handle(DataIntegrityViolationException ex, HttpServletResponse response) throws IOException {
ex.printStackTrace();
response.setHeader("Exception Message", ex.getMessage());
}
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
public void handle(HttpMediaTypeNotSupportedException ex, HttpServletResponse response) throws IOException {
ex.printStackTrace();
response.setHeader("Exception Message", ex.getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment