📜Introduction
In the previous article, we learned we should define a standard exception structure that is followed across all the RESTful services.

This article will discuss the implementation of generic exception handling for all resources.
📚Customizing the Exception Message
👉Create a new package with the name com.user_name.server.main.exception.
👉Create a class in java with the name ExceptionResponse in the above-created package.
👉Define the three fields timestamp, message, and details.
👉Generate the constructors with the help of fields.
👉Generate the getters, and setters aren’t needed.
Once the structure is defined, the Java implementation can be defined. We would always respond with a response in a specific manner whenever an exception occurred. The structure is the most crucial component and must be the independence of language.
ResponseEntityExceptionHandler class is one of the crucial classes in the Spring Framework. It is a foundation class for exceptions that is both abstract and provides centralized exception handling for all exception handler methods. We will add capabilities to handle this class and give specialized exception handling. All controllers, such as HelloWorldController and UserResource, are subject to this exception handling feature.
👉Create a new class with name CustomizedResponseExceptionHandler in the package com.username.server.main.exception and extends ResponseEntityExceptionHandler class.
👉Now we have to add @ControllerAdvice and @RestController annotations.
👉Now, Expand the following dependencies step-wise:
-
Maven Dependencies in the package explorer.
-
spring-webmvc-5.1.9.RELEASE.jar
-
org.springframework.web.servlet.mvc.method.annotation
Now openResponseEntityExceptionHandler.class.
👉Now we will copy the ResponseEntityMethod<Object> method from ResponseEntityExceptionHandler.class, then paste in CustomizedResponseExceptionHandler.java file.
👉Next, we will override the ResponseEntityMethod method. Rename the method name as handleAllExceptions().
👉We have to create the exception response structure.
👉Now create a ResponseEntity object and pass the exception response and HTTP status as arguments.
👉Now, let’s see the code of the CustomizedResponseExceptionHandler.java.
package com.username.server.main;
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.username.server.main.exception.ExceptionResponse;
//defining exception handling for all the exceptions
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
{
@ExceptionHandler(Exception.class)
//override method of ResponseExceptionHandler class
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request)
{
//creating exception response structure
ExceptionResponse exceptionResponse= new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
//returning exception structure and specific status
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
👉Send a Get request using Postman rest client. We receive the exception structure defined along with the Status: 500 Internal Server Error.
📚Changes must be made to the CustomizedResponseEntityExceptionHandler.java file if we wish to alter the Internal Server Error status to Not Found.
Customized ResponseExceptionHandler.java
package com.username.server.main;
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.username.server.main.exception.ExceptionResponse;
import com.username.server.main.user.UserNotFoundException;
//defining exception handling for all the exceptions
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
{
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request)
{
//creating exception response structure
ExceptionResponse exceptionResponse= new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
//returning exception structure and Internal Server status
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(UserNotFoundException.class)
//override method of ResponseEntityExceptionHandler class
public final ResponseEntity<Object> handleUserNotFoundExceptions(UserNotFoundException ex, WebRequest request)
{
ExceptionResponse exceptionResponse= new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
//returning exception structure and Not Found status
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
}
Again, send a Get request using Postman rest client. We receive the exception structure defined along with the Status: 500 Internal Server Error.
Frequently Asked Questions
Can generic exception classes be created?
The ability to create distinct catch blocks for various generic types should be possible to make the generic type on the exception class meaningful. However, due to type erasure, this is not feasible. The generic type information will be lost at runtime, leaving MyException<String> to be merely MyException.
Which of these combinations are allowed while implementing exception handling in programs?
A catch block is a block of statements that takes appropriate action when an exception occurs. A catch block is always used in combination with a try block.
What happens when an exception object is not caught and handled properly?
If an exception is not detected (within a catch block), the runtime system will abort the program (i.e., crash), and an exception message will print to the console.
Can parameterized types be used for handling exceptions?
Generic exceptions are not supported since there is no way to distinguish between generic exceptions with different type parameters in the catch clause because type parameters for generics are erased at runtime. You, therefore, have no choice but to use generic exceptions.
What happens when generic exceptions are spotted before specific ones?
You are putting the generic exception handler before all the catch blocks will display the general message even if it can handle all exceptions. Instead, it would help if you put it at the end. For every form of exception, you should always provide the user with a meaningful message rather than a general one.
Conclusion
This article taught us how to customize our error-handling code to implement generic exceptions. That’s all from the article. I hope you all like it.
If you want to learn more, check out our articles on Construct the Full K-ary Tree from its Preorder Traversal, Regular and Bipartite graphs, What Is Web2Py?, Why To Use Web2py?, Postbacks and Internationalization in web2py, Third Party Modules In Web2py, Tasks In Web2py, and XML in Web2py.
Happy Coding!




