Last active
October 31, 2020 11:44
-
-
Save jeffsheets/8b73620e0912afd95aa0 to your computer and use it in GitHub Desktop.
Handle REST Exceptions in Spring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See handled exceptions in the log file | |
log4j.logger.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=debug |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! This simple line saved me a headache :)