@Restcontrolleradvice **
A convenience annotation that combines @ControllerAdvice and @ResponseBody. It is designed for RESTful APIs where the return value of an exception handler is automatically serialized into the response body (typically as JSON or XML) instead of being resolved as a view.
**@ExceptionHandler
We can use @ExceptionHandler to annotate methods that Spring automatically invokes when the given exception occurs. We can specify the exception either with the annotation or by declaring it as a method parameter, which allows us to read out details from the exception object to handle it correctly. The method itself is handled as a Controller method.
EX:
@RestControllerAdvice
public class ExceptionController {
@ExceptionHandler(NullPointerException.class)
public String hanleNullPointerException(NullPointerException ex){
return "Error: "+ex.getMessage();
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public String hanleIllegalArgumentException(MethodArgumentNotValidException ex){
return "Error: "+ex.getMessage();
}
}
@valid:
It informs controller about the presence of @ExceptionHandler.
When an exception occurs,Spring container redirects the flow to corresponding Exception handler method
@PostMapping("/SaveBookDetails")
public String SaveBookDetails(@RequestBody @valid BookDetails bookDetails) {
log.info("entering ProcessBookDetailsController");
String ValueFromService=bookService.SaveBookDetails(bookDetails);
log.info("leaving ProcessBookDetailsController");
return ValueFromService;
}
To Enable validations in coding we have Spring Boot validation dependency.
For Spring Boot applications, the standard dependency for enabling Bean Validation is spring-boot-starter-validation. This starter provides the Jakarta Bean Validation API and Hibernate Validator as the default implementation.
Enabling Validation: Once the dependency is added, you must use annotations such as @valid or @Validated on your controller method parameters (e.g., @RequestBody) to trigger the validation process.
Standard Annotations: The dependency supports standard JSR-380 annotations including @NotNull, @notblank, @Size, @min, @max, and @Email.
Historical Note: Starting with Spring Boot 2.3, the validation starter is no longer included by default in spring-boot-starter-web or spring-boot-starter-webflux. You must add it explicitly to your project.
Error Handling: When validation fails, Spring Boot typically throws a MethodArgumentNotValidException, which can be captured using a Global Exception Handler with @ControllerAdvice.
pom.xml
Dependency Configurations
org.springframework.boot
spring-boot-starter-validation
org.springframework.boot
spring-boot-starter-validation-test
test
Code:
package LiBrary;
import jakarta.validation.constraints.*;
public class BookDetails {
@NotEmpty
String bookName;
@NotNull
@Positive
@Min(0)
@Max(50)
int bookId;
double price;
@NotBlank
@NotEmpty
String authorName;
String Genre;
@Email
String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getGenre() {
return Genre;
}
public void setGenre(String genre) {
Genre = genre;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
Setting default error message for valid annotations:
@NotEmpty(message="bookname cannot be blank")
String bookName;
@NotNull(message="Book id cannot be null")
@Positive(message="Book Id must be +ve")
@Min(0)
@Max(50)
int bookId;
double price;
@NotBlank(message="author name cannot be blank")
@NotEmpty(message="author name cannot be empty")
String authorName;
String Genre;
@Email(message="Not a valid email address")
String email;
error message:
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookDetails.bookId,bookId]; arguments []; default message [bookId]]; default message [Book Id must be +ve]] [Field error in object 'bookDetails' on field 'authorName': rejected value [ ]; codes [NotBlank.bookDetails.authorName,NotBlank.authorName,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
ResponseEntity:
public class ResponseEntity
extends HttpEntity
Extension of HttpEntity that adds an HttpStatusCode status code. Used in RestTemplate as well as in @Controller methods.
In RestTemplate, this class is returned by getForEntity() and exchange():
Snippet 1:
ResponseEntity entity = template.getForEntity("https://example.com", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();
Snippet 2
public ResponseEntity hanleIllegalArgumentException(MethodArgumentNotValidException ex){
Map errors=new HashMap();
//Code Snippet 1 - displays only key error message
ex.getBindingResult().getFieldErrors().forEach(Error->{
errors.put(Error.getField(),Error.getDefaultMessage());
});
return new ResponseEntity("validation error "+errors , HttpStatusCode.valueOf(400));
//Code Snippet 2 - displays all error with vast data
// return new ResponseEntity("validation error "+ex.getMessage() , HttpStatusCode.valueOf(400));
}
output:
validation error {authorName=author name cannot be blank, bookName=bookname cannot be blank, email=Not a valid email address, bookId=must be less than or equal to 50}
In above snippet we returned a map. we can also return a class
References:
Top comments (0)