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?
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);
}
}
One of best way or what I do is,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With