Mapping von Exceptions in Spring Boot
Oftmals müssen unchecked Exceptions aus dem Service-Layer einer Applikation in z.B. entsprechende HTTP-Fehlercodes konvertiert werden. Spring Boot bietet hierfür eine elegante Möglichkeit über die Annotation @ExceptionHandler an.
Beispiel
Es sollen alle ConstraintViolation-Fehler im Zusammenhang mit der Bean Validation API automatisch in 400er HTTP-Responses gemappt werden.
Hierzu erstellt man einfach einen neuen ControllerAdvice mit einer ExceptionHandler-Methode, die das Mapping beschreibt:
@ControllerAdvice public class ExceptionMapper { @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Validation error") @ExceptionHandler(ConstraintViolationException.class) public void validationError() { // Nothing to do } }
Möchte man noch weitere Exceptions mappen, kann man dies einfach durch Hinzufügen weiterer ExceptionHandler-Methoden in der ExceptionMapper-Klasse erreichen.