SpringBootResponseEntity不操纵HTTP响应
我在响应实体异常处理方面遇到了问题。正如所见,我的响应实体错误没有改变 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);
}
}
回答
您的代码中有一些错误,首先该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);
}
}