I am developing an application in Spring Boot. I was wondering what is the best way to handle exceptions. So following is my code,
ExceptionHandler.java
I am using @ControllerAdvice
. What is the best to use? @ControllerAdvice
or @RestControllerAdvice
?
@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> notFound(NotFoundException notFoundException) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND, notFoundException.getMessage());
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
}
}
And implemented service layer @Service
as follows,
@Override
public User update(User newUser) throws NotFoundException {
Optional<User> user = userRepository.findById(newUser.getId());
if (!user.isPresent()) throw new NotFoundException("Record Not Found!");
return userRepository.save(newUser);
}
In Controller.java
code is as follows,
@PutMapping
public User update(@RequestBody User user) {
User updatedUser = userService.update(user);
if (updatedUser == null) throw new SomeOtherException("Exception while Updating!");
return updatedUser;
}
So my questions are:
Is the above approach bad? Is it okay to throw exceptions in the service layer and will it catch automatically by @controlleradvice
? Or need to throw only in the controller? I am seeking the best practice to handle exceptions.
The way you used is perfectly fine.
As @ControllerAdvice/@RestControllerAdvice is used to handle exceptions globally throughout the controllers [flow].
You can throw exceptions in @Service layel also. [That is the same thing] ControllerAdvice will catch it.
You can customize your Exceptions your own way.