Как вернуть своё тело ответа в @ControllerAdvice?

Изучаю Spring и хочу научится работать с excepton в нём. У меня есть свой exception.

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class IncorrectEmailException extends RuntimeException {
    public IncorrectEmailException(String text) {
        super("Its not email - " + text);
    }
}

Как видно здесь я прописал @ResponseStatus с HttpStatus.BAD_REQUEST. В @ControllerAdvice я обрабатываю их таким способом.

@ControllerAdvice
public class Advice {

    @ExceptionHandler(IncorrectEmailException.class)
    public ResponseEntity<String> handleException(IncorrectEmailException e) {
        return returnMessage(e);
    }


    private ResponseEntity<String> returnMessage(Exception e){
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Я понимаю что я создаю новый ResponseEntity и возвращаю его с другим кодом ошибки. Но как мне вернуть в теле сообщение моей ошибки а httpstatus который я прописал в @ResponseStatus. Буду рад предложению другой реализации этой логики.


Ответы (1 шт):

Автор решения: Roman Konoval

Можно так:

private ResponseEntity<String> returnMessage(Exception e){
  ResponseStatus statusAnno = e.getClass().getAnnotation();
  HttpStatus httpStatus = statusAnno != null ? statusAnno.code() : HttpStatus.INTERNAL_SERVER_ERROR;
  return new ResponseEntity<>(e.getMessage(), httpStatus);
}
→ Ссылка