In this post and upcoming posts, I am going to explain, how can we achieve custom error handling in spring boot REST application.
Spring provides an abstract class ‘ResponseEntityExceptionHandler’ for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.
a. Handle Method argument not valid exception
b. Handle missing request parameter
c. Handle ConstrainViolationException
d. Handle MethodArgumentTypeMismatchException
For all the examples of this tutorial series, I am going to use following ApiError class to send error messages as response body.
ApiError.java
public class ApiError {
private HttpStatus status;
private String message;
private Object errors;
public ApiError(HttpStatus status, String message, Object errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getErrors() {
return errors;
}
public void setErrors(Object errors) {
this.errors = errors;
}
}
You can download the source code of this tutorial from this link.
No comments:
Post a Comment