If we write exception handler into the controller then we can not re-use it . Then need to write again which will violate co-usability rule.
So, to avoid code duplication we can define global exception handler using @ControllerAdvice.
@ControllerAdvice:
--Its similar to pre-processor/filter.
--Pre process request to controller.
-- Preprocess responses to handle exception.
--Perfect for global exception handling.
let's refactor our previous exception handling code-
@ControllerAdvice
public class StudentRestHandlerException{
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFound exc){
StudentErrorResponse errorResponse = new StudentErrorResponse();
errorResponse.setStatus(HttpStatus.Not_found.value());
errorResponse.setMessage(exc.getMessage());
errorResponse.setTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);// will return a json .jackson will convert the pojo to json .
}
What if the user request using character in request parameter without giving integer value . then server again will show an ugly message .so we should handle it . so lets create another exception handler ..
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(Exception ex){
StudentErrorResponse errorResponse = new StudentErrorResponse();
errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());
errorResponse.setMessage(exc.getMessage());
errorResponse.setTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
No comments:
Post a Comment