Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to handle exception in Spring Boot?

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.

like image 972
H Athukorala Avatar asked Nov 07 '25 11:11

H Athukorala


1 Answers

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.

like image 149
Nakul Goyal Avatar answered Nov 09 '25 01:11

Nakul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!