I want to handle exceptions in my Rest spring boot application. I know that with @ControllerAdvice and ResponseEntity I can return a custom object that will represent my error, but what I want is to add a new field to the body of the exesting exception that's all.
I created a custom Exception that inherit RuntimeException with an extra attribute, a list of string :
@ResponseStatus(HttpStatus.CONFLICT)
public class CustomException extends RuntimeException {
private List<String> errors = new ArrayList<>();
public CustomException(List<String> errors) {
this.errors = errors;
}
public CustomException(String message) {
super(message);
}
public CustomException(String message, List<String> errors) {
super(message);
this.errors = errors;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
}
In my controller I just throw this custom exception this way:
@GetMapping("/appointment")
public List<Appointment> getAppointments() {
List<String> errors = new ArrayList<>();
errors.add("Custom message");
throw new CustomException("This is my message", errors);
}
When I test my Rest endpoint with postman, it seems like that spring boot doesn't marshall my errors field, the response is :
{
"timestamp": "2017-06-05T18:19:03",
"status": 409,
"error": "Conflict",
"exception": "com.htech.bimaristan.utils.CustomException",
"message": "This is my message",
"path": "/api/agenda/appointment"
}
I can go for a custom object with @ControllerAdvice if I can get the "path" and "timestamp" fields from the exception but there's no getters for these two attributes.
Thank you.