Billing Software using Spring Boot Integrating Centralized Exception handling

Billing Software using Spring Boot Integrating Centralized Exception handling
Spring boot exception handling

Centralized exception handling is a great feature in Spring Boot. Once we created a common method for a particular exception we can reuse that exception handler method anywhere in your application. The following three things are important to implement centralized exception handling.

1) ResponseEntityExceptionHandler
2) @ControllerAdvice

The above two friends will help you to implement the centralized exception handler. To implement our generic Exception handling method, we need to create a new class. This must extend from ResponseEntityExceptionHandler.

@ControllerAdvice
public class BillingExceptionHandler extends ResponseEntityExceptionHandler {

Syntax to create a generic exception handler class
@ExceptionHandler(Your Exception handler class)
When you create an exception handling method, the method must be annotated with the above annotation and you need to pass your Exception class as a parameter which you want to handle. For example. if you want to handle the “InvalidInputException” we have to define our method like below.

@ExceptionHandler(InvalidInputException.class)
public final ResponseEntity<Object> invalidInputException(InvalidInputException ex, WebRequest request) throws Exception {
Your method body
}

In the above method,I named it as “invalidInputException(InvalidInputException ex,WebRequest request)
This method must have two-parameter, one is The exception class which you want to handle and the second one is Web Request. if you need any request data, you can use this parameter.

Once you define this, you need to implement your method logic on how you want to handle the exception. Inside the method, I have given the following implementation.

ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), Utils.currentDateTime());
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);

The “ErrorMessage” is my own class, it has a very simple implementation. The ErrorMessage constructor accepts two parameter one is error message and localDatatime. Using the second parameter I can pass the current date and time. I am initializing the ErrorMessage constructor and passing the error message and LocalDateTime object. Then, I am passing the Error Message object in the ResponseEntity Constructor and Error status as a Bad Request. Like below.

return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);

Now, this error message will display on the client-side whenever we throw the InvalidaInputException.
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ErrorMessage {

private String errorMessage;
private LocalDateTime localDateTime;

}

Below is the complete method implementation.
@ExceptionHandler(InvalidInputException.class)
public final ResponseEntity<Object> invalidInputException(InvalidInputException ex, WebRequest request) throws Exception {
ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), Utils.currentDateTime());
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}

In our billing System App, I am throwing “InvalidInputException” Multiple Places” wherever we throw “InvalidInputException”, the above method automatically called by Spring Framework and displays the error as a response on the client-side.

Following places I am throwing “InvalidInputException”

JWTRequestFilter
inside the catch block, I am throwing “InvalidInputException”

} catch (ExpiredJwtException e) {
throw new InvalidInputException(e.getMessage());
} catch (BadCredentialsException e) {
throw new InvalidInputException(e.getMessage());

JWTUtils
I am throwing inside isValidToken()” method like below

if (tokenType.equals(TokenType.REFRESH_TOKEN)) {
if (isRefreshTokenExpired(token)) {
errorList.add(“Invalid Refresh Token: Refresh Token is expired”);
}
}
if (tokenType.equals(TokenType.ACCESS_TOKEN)) {
if (isAccessTokenExpired(token)) {
errorList.add(“Invalid Access Token: Access Token is expired”);
}
}
if (!errorList.isEmpty()) {
throw new InvalidInputException(errorList);
}

UserValidator
Inside the “validate()” method,I am calling if “validationMessage” object contains any error.

if (!validationMessages.isEmpty()) {
throw new InvalidInputException(validationMessages);
}

I am just throwing the error in the above programs, the spring framework reusing the below method for handling the “InvalidInputException”. We don’t have to write try….catch all the places. define one place, we can call it anywhere by throwing a respective exception. This is the magic of Exception handling in Spring Boot, that’s why I call it Centralized Exception handling.

@ExceptionHandler(InvalidInputException.class)
public final ResponseEntity<Object> invalidInputException(InvalidInputException ex, WebRequest request) throws Exception {
ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), Utils.currentDateTime());
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}

Watch the following two YouTube for Centralized Exception handling
https://youtu.be/zavGP9uD7D8
https://youtu.be/vRGQt_wx1aw

You can pull the latest source code from the following GitHub link:
https://github.com/sureshstalin/billingsystem 


Please follow our ITGARDEN YouTube channel for Billing System Project development work using Spring Boot. The Project source code absolutely free. This project is very good for who is looking for real-time project experience in Spring Boot. To understand the Billing System Project code, watch all Billing System related YouTube videos from this link. Click Here
Our YouTube Channel
https://www.youtube.com/channel/UChj5CeuWaHIFr4RkXoG3iJA?view_as=subscriber
Please follow me on Medium.com for all billing system related stories and Java-based technical Articles
https://suresh-stalin.medium.com/
Note: To find all billing System related stories find “billing system itgarden” in medium.com

Close Menu
×
×

Cart