0

I was wondering how it is possible to return a custom status code and message from a rest endpoint when throwing an exception. The code below allows me to throw my own, custom status code 571 when UserDuplicatedException is thrown, but I cant seem to fnd a way to give it an additional message or reason for the error. Can you help please?

@ControllerAdvice
public class ExceptionResolver {

@ExceptionHandler(UserDuplicatedException.class)
public void resolveAndWriteException(Exception exception, HttpServletResponse response) throws IOException {
    int status = 571;
    response.setStatus(status);
}

}

1
  • HttpServletResponse has a sendError method, but that has other implications documented in its javadoc. Look into it. Commented Nov 10, 2017 at 19:59

1 Answer 1

1

This should be straight forward.

Create custom error class:

public class Error {
    private String statusCode;
    private String message;
    private List<String> errors;
    private Date date;

    public Error(String status, String message) {
        this.statusCode = status;
        this.message = message;
    }

    //Getters - Setters 
}

And in your @ControllerAdvice as

@ControllerAdvice
public class ExceptionResolver {

    @ExceptionHandler(UserDuplicatedException.class)
    public ResponseEntity<Error> resolveAndWriteException(UserDuplicatedException e) throws IOException {
        Error error = new Error("571", e.getMessage());
        error.setErrors(//get your list or errors here...);
        return new ResponseEntity<Error>(error, HttpStatus.Select-Appropriate); 
    }
}
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.