Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

OpenFeign服务方返回null对象,调用方得到的却是一个具体对象,但是字段为null

问题描述

OpenFeign服务方返回null对象,调用方得到的却是一个具体对象,但是字段为null

问题出现的环境背景及自己尝试过哪些方法

在做注册功能的时候通过Auth模块传递参数username去user模块查找,然后返回user对象(无论是否为null),然后对user模块返回内容进行检验,根据是否为空进行后面的逻辑操作,但是当我user模块返回的user对象为null的时候auth模块得到的user对象不为Null,但是他的字段为null导致判空操作不命中.目前是通过获取返回的userId进行判空进行替代解决方案

相关代码

AuthController

  @PostMapping( "/regist/password" )
 public String regist( @RequestBody @Valid UserRegistByPasswordReqVo userRegistByPasswordReqVo ,
 BindingResult result ){
 if( result.hasErrors() ) {
 throw new BusinessException( "-1" , Objects.requireNonNull( result.getFieldError() ).getDefaultMessage() );
 }
 User user = userService.findUser( userRegistByPasswordReqVo.getUsername() );
 //目前的替代方案
 //if( user.getId() != null ) {
 //throw new AuthException( //AuthErrorCode.ACCOUNT_EXIST_USERNAME );
 }
// 通过判断user是否为null的方案
  Optional.ofNullable( user ).ifPresent( u -> {
   if( u.getId() != null ) {throw new AuthException( AuthErrorCode.ACCOUNT_EXIST_USERNAME );}
  } );
 userService.addUser( userRegistByPasswordReqVo );
 return "success";
 }

Auth模块的UserService

@FeignClient( "demos-user" )
public interface UserService{
  
@GetMapping( "/user/{username}" )
 User findUser( @PathVariable String username );
 @PostMapping("/user")
 void addUser( UserRegistByPasswordReqVo userRegistByPasswordReqVo );
}

UserController

@PostMapping
 @IgnoreResponseAdvice(errorDispose = false)
 public User addUser( @RequestBody UserRegistByPasswordReqVo userRegistByPasswordReqVoVo ){
 return userService.addUser( userRegistByPasswordReqVoVo );
//  throw new UserException( UserErrorCode.TEST_ERROR );
 }
 @GetMapping( "/{username}" )
 public User findUser( @PathVariable String username ){
 try {
 Thread.sleep( 2000L );
 } catch( InterruptedException e ){
 e.printStackTrace();
 }
 return userService.findByUsername( username );
 }

你期待的结果是什么?实际看到的错误信息又是什么?

期待的结果:
userService.findUser()返回Null的时候

Optional.ofNullable( user ).ifPresent( u -> {
   if( u.getId() != null ) {throw new AuthException( AuthErrorCode.ACCOUNT_EXIST_USERNAME );}
  } );

不会抛出异常,user为null

实际看到的错误:
image.png

findUser查询出的对象为null,
image.png
通过debug可以看到user为null,没有地址值,而调用方的断点却显示有地址值,字段为null.
image.png
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

找到问题了,是因为我之前引用了spring-cloud-purgeteam导致的,取消引用就好了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...