Spring Boot ResponseEntity 不操纵 HTTP 响应

Roj*_*hat 0 error-handling spring httpresponse http-response-codes spring-boot

我在响应实体异常处理方面遇到了问题。正如所见,我的响应实体错误没有改变 HTTP 响应。

我的代码

      public ResponseEntity<User> retriveUser(@PathVariable int id){
      Optional<User> foundUser;
      foundUser= userRepo.findById(id);
      
      if(foundUser.get()==null) {
          return new ResponseEntity<>(foundUser.get(),HttpStatus.HttpStatus.NOT_FOUND);
          }
      
      else {
          return new ResponseEntity<>(foundUser.get(),HttpStatus.OK);
          }    
  }  
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

İsm*_* Y. 5

您的代码中有一些错误,首先该foundUser.get()==null部分没有进入 if 块,因为它抛出了错误。你可以查看java文档,找出你抛出错误的原因。

  • 它也需要HttpStatus.NOT_FOUND代替HttpStatus.HttpStatus.NOT_FOUND.
  • 在“Not Found”行中,使optionalUser.get()方法不报错;你也必须删除它。
@GetMapping("/user/{id}")
public ResponseEntity<User> retrieveUser(@PathVariable int id) {
   Optional<User> optionalUser = userRepo.findById(id);
   if (!optionalUser.isPresent()) {
      return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
   } else {
      return new ResponseEntity<>(optionalUser.get(), HttpStatus.OK);
   }
}
Run Code Online (Sandbox Code Playgroud)