ResponseStatusException Error handling in Simple language

I am going to answer three questions regarding ResponseStatusException: What, Why and How?

The first one is What is ResponseStatusException? Here is the answer:

  1. ResponseStatusException is a class in Spring that is used for error handling in our RESTful API's
  2. It is the base class for exceptions which is used for applying status code to an HTTP Response.
  3. It is a run time exception

Constructor class of ResponseStatusException includes:

status - HTTP status like 200, 404 etc.

reason - message

cause - a throwable cause of RSE

Why we use it?

Very simple answer, for error handling. Suppose a user wants to get user for a user id which is not present in the repository, in that case, instead of returning a string message "Not found", if we return a DTO which contains HTTP status code, message and a cause then it would make more sence.

How to use it?

Step 1: First we define our exception by extending the Exception class

Step 2: We use try-catch block in the controller and catch the exception and then return HTTP-status response

Step 3: In Service layer, we check and throw an exception if object not present

Below is an example for implementing ResponseStatusException for a service getUserById

First, we define our own custom UserNotFoundException by extending Exception class


public class UserNotFoundException extends Exception {

    public UserNotFoundException(String message) {
        super(message);
    }

}

And then using it in controller and service layers in all apis. Below is an example for 404-Not Found HTTP status code

//Controller Layer
@GetMapping("/users/{id}")
    public User getUserById(@PathVariable("id") Long userId){
        try {
            return userService.getUserById(userId);
        }catch (UserNotFoundException e){
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
}
//Service Layer
public User getUserById(Long userId) throws UserNotFoundException {
        Optional<User> user=userRepository.findById(userId);
        if(user.isEmpty()){
            throw new UserNotFoundException("User not found in repository");
        }
        return user.get();
}

This is the response for the above API in postman:

Screenshot from 2021-04-10 22-09-05.png

If you want to remove the trace part from the response object, we can use one property to disallow it server.error.include-stacktrace=never in application.properties file

After doing that change the response in postman changes to this:

Screenshot from 2021-04-10 22-10-13.png

So that was all about error handling through ResponseStatusException class in this post.

Thank you for reaching here.