Custom Exception Handling Using ResposneEntityExceptionHandler in Java, Spring:
Sometime Java developers need to create custom exceptions, i.e. Exceptions which are not defined in JDK. Spring provides a exception handler class which help us to handle custom exceptions gracefully.
Here is complete code example of creating custom or user defined exception in Java. In this example I created UserNotFoundException and RestResponseEntityExceptionHandler class.
Here is complete code example of creating custom or user defined exception in Java. In this example I created UserNotFoundException and RestResponseEntityExceptionHandler class.
Steps for handling Custom Exception:
1. Create Custom Java Class which will inherit Exception Class
1. Create Custom Java Class which will inherit Exception Class
public class UserNotFoundException extends Exception {
private static final String DEFAULT_MESSAGE = "User not found!";
public UserNotFoundException() {
super(DEFAULT_MESSAGE);
}
public UserNotFoundException(String message) {
super(message);
}
}
ResponseEntityExceptionHandler: A class that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.
This class provides an @ExceptionHandler for handling standard Spring MVC exceptions that returns a ResponseEntity.
@ControllerAdvice: A class annotated with it will act as global handler class for all controllers. It is used to define @ExceptionHandler methods that apply to all @RequestMapping methods.
3. Create service which will throw UserNotFoundException.class if user doesn't found in the DB.
public interface UserService {
User findByEmailId(String emailId) throws UserNotFoundException;
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User findByEmailId(String emailId) throws UserNotFoundException {
if ((emailId == null) || (emailId == "")) {
throw new IllegalArgumentException("userId not found ");
}
User user = userRepository.findByEmail(emailId);
if (user == null) {
throw new UserNotFoundException();
}
return user;
}
}
private static final String DEFAULT_MESSAGE = "User not found!";
public UserNotFoundException() {
super(DEFAULT_MESSAGE);
}
public UserNotFoundException(String message) {
super(message);
}
}
2. Create Exception Handler Java Class
/**
* REST exception handlers defined at a global level for the application
*
**/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {UserNotFoundException.class})
protected ResponseEntity<RestResponse> handleUserNotFound(UserNotFoundException ex, WebRequest request) {
return handleException(ex.getMessage(), HttpStatus.FORBIDDEN);
}
private ResponseEntity<RestResponse> handleException(String message, HttpStatus status) {
LOGGER.error(message);
return new ResponseEntity<RestResponse>(new RestResponse(Boolean.FALSE, ImmutableList.of(message), null), status);
}
}
This class provides an @ExceptionHandler for handling standard Spring MVC exceptions that returns a ResponseEntity.
@ControllerAdvice: A class annotated with it will act as global handler class for all controllers. It is used to define @ExceptionHandler methods that apply to all @RequestMapping methods.
3. Create service which will throw UserNotFoundException.class if user doesn't found in the DB.
public interface UserService {
User findByEmailId(String emailId) throws UserNotFoundException;
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User findByEmailId(String emailId) throws UserNotFoundException {
if ((emailId == null) || (emailId == "")) {
throw new IllegalArgumentException("userId not found ");
}
User user = userRepository.findByEmail(emailId);
if (user == null) {
throw new UserNotFoundException();
}
return user;
}
}
4. Create Controller which will call service method
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/findby-email", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<RestResponse> findByEMail(@RequestParam String email) throws UserNotFoundException {
return new ResponseEntity<RestResponse>(new RestResponse(Boolean.TRUE, "Succesfully Logged In!", userService.findByEmailId(email)), HttpStatus.OK);
}
@ResponseBody
public ResponseEntity<RestResponse> findByEMail(@RequestParam String email) throws UserNotFoundException {
return new ResponseEntity<RestResponse>(new RestResponse(Boolean.TRUE, "Succesfully Logged In!", userService.findByEmailId(email)), HttpStatus.OK);
}
}
For complete running application refer Github Repository
Keywords: GloabalExcetionHandling, SpringMVC, ResponseEntityExceptionHandler, @ControllerAdvice, REST