[英]How to handle exception between spring REST web services
I have two web services based on Spring boot, REST and MVC. 我有两个基于Spring引导的Web服务,REST和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.
第一个服务(DesignService)项目调用第二个服务(UserService)项目,将电子邮件作为参数传递,并取回用户对象(User.java)。 How can I handle if no user is found.
如果找不到用户该怎么办。
DesignService project DesignService项目
repository.java 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 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 仓库.java
public User getUser(String email){
//query db for user
return user; //what to return if no user is found [3]
}
* excuse me if am wrong in some syntax as I have typed it directly . *如果我在直接输入某些语法上错误,请原谅。
Return null, or if you're on Java 8, an empty Optional 返回null,或者如果您使用的是Java 8,则返回空的Optional
If no user is found, return an empty Response with a 404 (NOT_FOUND) status, ie 如果未找到用户,则返回状态为404(NOT_FOUND)的空响应,即
new ResponseEntity(HttpStatus.NOT_FOUND);
新的ResponseEntity(HttpStatus.NOT_FOUND);
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).
您应该正在执行GET,从外观上看,您的请求映射应仅支持GET(方法= RequestMethod.GET)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.