Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices to handler or throw exceptions in a Spring Boot application?

I've developed a rest api using Spring Boot. In one of my service methods, I throw a ServletException, in case a specific user is not found. I am wondering if that is the best way to do that, I mean, is that the right layer to thrown the exception?

like image 247
user3619911 Avatar asked Jan 28 '26 15:01

user3619911


2 Answers

Creating a custom exception type is a better idea than using ServletException. In order to handle an exception you can use @ControllerAdvice. First create custom exception type:

public class UserNotFoundException extends RuntimeException {

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

Assuming that your controller and service look more or less like this:

@RestController
@RequestMapping("users")
class UserController {

  private final UserService userService;

  UserController(UserService userService) {
    this.userService = userService;
  }

  @GetMapping
  List<String> users() {
    return userService.getUsers();
  }
}

@Service
class UserService {

  List<String> getUsers() {
    // ...
    throw new UserNotFoundException("User not found");
  }
}

You can handle you UserNotFoundException using @ControllerAdvice

@ControllerAdvice
class CustomExceptionHandler {

  @ExceptionHandler({UserNotFoundException.class})
  public ResponseEntity<Object> handleUserNotFoundException(UserNotFoundException exception) {
    return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
  }
}
like image 80
k13i Avatar answered Jan 30 '26 05:01

k13i


One of best way or what I do is,

  1. Check data / parameters for valid data( e.g Null check sometime manually using if statement).
  2. Checking data / parameters for size (like file size)
  3. checking data or parameters for valid range also data type, do typecasting if not in valid type (like String, Long, Integer etc).
  4. Raise a message and return to that API, if the data / parameters are not valid before system raise an exception
like image 23
Nitin Dhomse Avatar answered Jan 30 '26 05:01

Nitin Dhomse