Ondrej Bozek
Ondrej Bozek

Reputation: 11481

Exception handling in Spring MVC - exception description

I have exception anotated with @ResponseStatus like this:

@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY, reason = "Restrioctions violated. Need confirmation.")
@ResponseBody
public class RestrictionExceptions extends Exception {

    private List<RestrictionViolation> restrictionViolations;

But when exception is raised there is only HTTP status code and reason from @ResponseStatus declaration. Is it possible to include also restrictionViolations in error response body?

I want to keep exception declaration in exception itself, I don't want to introduce some exception handling method in controller if it's possible.

Upvotes: 0

Views: 124

Answers (1)

Jannik Weichert
Jannik Weichert

Reputation: 1673

You could create an ErrorResource with the fields you want to have in the body:

public class ErrorResource {
    private String reason;
    private String value;
    private List<RestrictionViolation> restrictionViolations;
    ....
}

and process the Exception in a Handler:

@ControllerAdvice
public class RestrictionExceptionsHandler {

@ExceptionHandler({ RestrictionExceptions.class })
protected ResponseEntity<ErrorResource> handleInvalidRequest(Exception exception) {
    RestrictionExceptions restrictionExceptions = (RestrictionExceptions) exception;

    ErrorResource error = new ErrorResource();
    Class clazz = exception.getClass();
    if(clazz.isAnnotationPresent(ResponseStatus.class)){
         ResponseStatus responseStatus = (ResponseStatus) clazz.getAnnotation(ResponseStatus.class);
        error.setValue(responseStatus.value());
        error.setReason(responseStatus.reason());
    }
    error.setRestrictionViolations(restrictionExceptions.getRestrictionViolations());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    return new ResponseEntity<ErrorResource>(error, error.getValue());
}
}

Upvotes: 1

Related Questions