404 if Not Found the resource in Spring Boot
For the Rest API we have to add proper Error Code as response to identify the Response
UserResourceController.java
@RestController
public class UserResourceController {
private UserDaoService userDaoService;
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) throws UserPrincipalNotFoundException {
User user = userDaoService.findOne(id);
return user;
}
}
UserDaoService.java
@Component
public class UserDaoService {
private static List<User> users = new ArrayList<>();
private static int usersCount = 0;
static {
users.add(new User(++usersCount, "Khan", LocalDate.now().minusYears(25)));
users.add(new User(++usersCount, "pathan", LocalDate.now().minusYears(50)));
users.add(new User(++usersCount, "tigher", LocalDate.now().minusYears(52)));
users.add(new User(++usersCount, "jim", LocalDate.now().minusYears(40)));
users.add(new User(++usersCount, "kabir", LocalDate.now().minusYears(35)));
}
public User findOne(int id) {
Predicate<? super User> predicate =user -> user.getId().equals(id);
return users.stream().filter(predicate).findFirst().get();
}
}
with Given Above API call with existing User
Given above API call with not present id than will give you server error like given Below
@Component
public class UserDaoService {
public User findOne(int id) {
Predicate<? super User> predicate =user -> user.getId().equals(id);
return users.stream().filter(predicate).findFirst().orElse(null);
}
}
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) throws UserPrincipalNotFoundException {
User user = userDaoService.findOne(id);
if(user == null) {
throw new UserNotFoundException("id:"+id);
}
return user;
}
Comments
Post a Comment