0

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.

1 Answer 1

1

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());
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.