Global Exception Handler in Spring Boot
GlobalExceptionHandler mechanism centralizes the exception handling and return an appropriate response. Instead of just getting “Internal Server Error” we also get log message regarding what has gone wrong.
Step 1 → Create an exception which extends RuntimeException class. The exception class can contain the error message.
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
super("Resource not found on server !");
}
public ResourceNotFoundException(String message) {
super(message);
}
}
Step 2 → Create a class which can store API Response.
import org.springframework.http.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ApiResponse {
private String message;
private boolean success;
private HttpStatus status;
}
Step 3 → Create GlobalExceptionHandler Class with @RestControllerAdvice. This class will have Exception Handler methods (with @ExceptionHandler).
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.movie_rating.user.service.payload.ApiResponse;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse> handlerResourceNotFoundException(ResourceNotFoundException resourceNotFoundException){
String message = resourceNotFoundException.getMessage();
ApiResponse response = ApiResponse.builder().message(message).success(true).build();
return new ResponseEntity<ApiResponse>(response, HttpStatus.NOT_FOUND);
}
}
Step 4 → We can now use this Exception Class in our code.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.movie_rating.user.service.entities.UserEntity;
import com.movie_rating.user.service.exceptions.ResourceNotFoundException;
import com.movie_rating.user.service.repositories.UserRepository;
@Service
public class implUserService implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public UserEntity getUser(String userId) {
return userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("Resource with given id is not found on server : "+userId));
}
}
You will such response with an error message when the Application throws an exception →
Subscribe to my newsletter
Read articles from Prashant Katare directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Prashant Katare
Prashant Katare
Experienced Spring Boot Developer with over 3+ years of expertise in developing scalable and high-performance web applications and microservices. Proficient in Java and Spring Boot frameworks, with hands- on experience in RESTful APIs and Microservices architecture. Adept at building secure, database-driven applications and integrating various third- party services. Strong problem-solving skills with a focus on delivering clean, maintainable, and efficient code.