levant pied
levant pied

Reputation: 4501

Spring Boot @ControllerAdvice @ExceptionHandler content type via an annotation

I know e.g. status can be set via an annotation:

@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleMyException(MyException myException) {
    return myException.getMessage();
}

I know I can make a ResponseEntity with the appropriate content type like this:

@ExceptionHandler(MyException.class)
public ResponseEntity<String> handleMyException(MyException myException) {
    return ResponseEntity
        .badRequest()
        .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
        .body(myException.getMessage());
}

Is it possible to set the content type via annotation only, i.e. something like this:

@ExceptionHandler(MyException.class)
@ContentType(MediaType.TEX_PLAIN_VALUE)
public String handleMyException(MyException myException) {
    return myException.getMessage();
}

I couldn't find an annotation that would do that.

Upvotes: 2

Views: 570

Answers (1)

J.P
J.P

Reputation: 565

According to spring documentation (same for boot as well), you can set only @ResponseStatus annotation with ExceptionHandler.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html

Upvotes: 1

Related Questions