问题描述
OpenFeign服务方返回null对象,调用方得到的却是一个具体对象,但是字段为null
问题出现的环境背景及自己尝试过哪些方法
在做注册功能的时候通过Auth模块传递参数username去user模块查找,然后返回user对象(无论是否为null),然后对user模块返回内容进行检验,根据是否为空进行后面的逻辑操作,但是当我user模块返回的user对象为null的时候auth模块得到的user对象不为Null,但是他的字段为null导致判空操作不命中.目前是通过获取返回的userId进行判空进行替代解决方案
相关代码
AuthController
@PostMapping("/regist/password")
publicStringregist(@RequestBody@ValidUserRegistByPasswordReqVouserRegistByPasswordReqVo,
BindingResultresult){
if(result.hasErrors()){
thrownewBusinessException("-1",Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
}
Useruser=userService.findUser(userRegistByPasswordReqVo.getUsername());
//目前的替代方案
//if(user.getId()!=null){
//thrownewAuthException(//AuthErrorCode.ACCOUNT_EXIST_USERNAME);
}
//通过判断user是否为null的方案
Optional.ofNullable(user).ifPresent(u->{
if(u.getId()!=null){thrownewAuthException(AuthErrorCode.ACCOUNT_EXIST_USERNAME);}
});
userService.addUser(userRegistByPasswordReqVo);
return"success";
}
Auth模块的UserService
@FeignClient("demos-user")
publicinterfaceUserService{
@GetMapping("/user/{username}")
UserfindUser(@PathVariableStringusername);
@PostMapping("/user")
voidaddUser(UserRegistByPasswordReqVouserRegistByPasswordReqVo);
}
UserController
@PostMapping
@IgnoreResponseAdvice(errorDispose=false)
publicUseraddUser(@RequestBodyUserRegistByPasswordReqVouserRegistByPasswordReqVoVo){
returnuserService.addUser(userRegistByPasswordReqVoVo);
//thrownewUserException(UserErrorCode.TEST_ERROR);
}
@GetMapping("/{username}")
publicUserfindUser(@PathVariableStringusername){
try{
Thread.sleep(2000L);
}catch(InterruptedExceptione){
e.printStackTrace();
}
returnuserService.findByUsername(username);
}
你期待的结果是什么?实际看到的错误信息又是什么?
期待的结果:
当userService.findUser()返回Null的时候
Optional.ofNullable(user).ifPresent(u->{
if(u.getId()!=null){thrownewAuthException(AuthErrorCode.ACCOUNT_EXIST_USERNAME);}
});
不会抛出异常,user为null
实际看到的错误:
![](https://img-bbs.csdn.net/upload/202012/16/1608084769_272250.png)
findUser查询出的对象为null,
![](https://img-bbs.csdn.net/upload/202012/16/1608084828_807683.png)
通过debug可以看到user为null,没有地址值,而调用方的断点却显示有地址值,字段为null.
![](https://img-bbs.csdn.net/upload/202012/16/1608084858_152143.png)
![](https://img-bbs.csdn.net/upload/202012/16/1608084858_381216.png)
分 -->
|