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


Request

Response

Given above API call with not present id than will give you server error like given Below


Request of 786 User which does not exist in the system
Response are getting as 500 Internal Server Error which is not handled


Now We have to Handle and Give 404 instead of 500 as this is not Found means 404
Step 1: Add code for if User is not found return Null added .orElse(null) if not found

@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);

}

}

Step 2: Add your Own User Defined UserNotFound Runtime Exception

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);

}

}



Step 3: Added for Response is getting as Null to throw user Defined UserNotFound Exception

@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;

}



will get User Defined 404 Not Found Response to the Client for more Understandable to Client





Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API