简体   繁体   English

如何处理Spring REST Web服务之间的异常

[英]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]
}
  1. what to do at point [3] if user not found .throw exception or return empty user object? 如果找不到用户抛出异常或返回空用户对象,在点[3]处该怎么办?
  2. what to do at [2] any excpetion handling / http status code / ... ?? 在[2]任何异常处理/ http状态码/ ...上做什么?
  3. how do I handle these exceptions at [1]. 我如何在[1]处理这些异常。 I dont think checking for user as null is a good idea. 我不认为检查用户为null是个好主意。

* 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 返回null,或者如果您使用的是Java 8,则返回空的Optional

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

  1. Catch org.springframework.web.client.HttpClientErrorException 捕获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). 您应该正在执行GET,从外观上看,您的请求映射应仅支持GET(方法= RequestMethod.GET)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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