简体   繁体   中英

How to handle exception between spring REST web services

I have two web services based on Spring boot, REST and MVC. The first service(DesignService) project calls the second service(UserService) project passing a email as parameter and gets the user object(User.java) back. How can I handle if no user is found.

DesignService project

repository.java

@Autowired
RestTemplate restTemplate;
getUser(String email){
    restTemplate.postForObject("url for User service",email,User.class); //calls User service for Object[1]
}

UserService

UserController.java

@RequestMapping()
public ResponseEntity<User> getUser(@RequestBody String email){
    User user = repository.getUser(email); //return a user object from DB
    return new ResponseEntity<User>(user);[2]
}

Repository.java

public User getUser(String email){
//query db for user 
return user; //what to return if no user is found [3]
}
  1. what to do at point [3] if user not found .throw exception or return empty user object?
  2. what to do at [2] any excpetion handling / http status code / ... ??
  3. how do I handle these exceptions at [1]. I dont think checking for user as null is a good idea.

* excuse me if am wrong in some syntax as I have typed it directly .

  1. Return null, or if you're on Java 8, an empty Optional

  2. If no user is found, return an empty Response with a 404 (NOT_FOUND) status, ie

new ResponseEntity(HttpStatus.NOT_FOUND);

  1. Catch org.springframework.web.client.HttpClientErrorException

Finally, why are you POSTing to an endpoint that only returns a resource? You should be doing a GET, and from the looks of it, your request mapping should only support GET (method = RequestMethod.GET).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM