Skip to content

Instantly share code, notes, and snippets.

@jeffsheets
Last active October 31, 2020 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffsheets/8b73620e0912afd95aa0 to your computer and use it in GitHub Desktop.
Save jeffsheets/8b73620e0912afd95aa0 to your computer and use it in GitHub Desktop.
Handle REST Exceptions in Spring
/**
* REST exception handlers defined at a global level for the application
*/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);
/**
* Catch all for any other exceptions...
*/
@ExceptionHandler({ Exception.class })
@ResponseBody
public ResponseEntity<?> handleAnyException(Exception e) {
return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* Handle failures commonly thrown from code
*/
@ExceptionHandler({ InvocationTargetException.class, IllegalArgumentException.class, ClassCastException.class,
ConversionFailedException.class })
@ResponseBody
public ResponseEntity handleMiscFailures(Throwable t) {
return errorResponse(t, HttpStatus.BAD_REQUEST);
}
/**
* Send a 409 Conflict in case of concurrent modification
*/
@ExceptionHandler({ ObjectOptimisticLockingFailureException.class, OptimisticLockingFailureException.class,
DataIntegrityViolationException.class })
@ResponseBody
public ResponseEntity handleConflict(Exception ex) {
return errorResponse(ex, HttpStatus.CONFLICT);
}
protected ResponseEntity<ExceptionMessage> errorResponse(Throwable throwable,
HttpStatus status) {
if (null != throwable) {
log.error("error caught: " + throwable.getMessage(), throwable);
return response(new ExceptionMessage(throwable), status);
} else {
log.error("unknown error caught in RESTController, {}", status);
return response(null, status);
}
}
protected <T> ResponseEntity<T> response(T body, HttpStatus status) {
log.debug("Responding with a status of {}", status);
return new ResponseEntity<>(body, new HttpHeaders(), status);
}
}
# See handled exceptions in the log file
log4j.logger.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=debug
@franDayz
Copy link

Thanks! This simple line saved me a headache :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment