我可以发送一个错误Map和一个响应对象作为响应吗?正确的方法是什么?

dsf9zpds  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(345)

我有一个spring rest端点,它接受一个user对象并返回另一个userobject作为响应。我的控制器方法如下所示:

@PostMapping
public UserResponse createUser(@RequestBody UserDetailsRequestModel userDetails)
            throws Exception {

        UserRest userResponse= new UserRest();

        ModelMapper modelMapper = new ModelMapper();
        UserDto userDto = modelMapper.map(userDetails, UserDto.class);
        userDto.setRoles(new HashSet<>(Arrays.asList(Roles.ROLE_USER.name())));
        UserDto createdUser = userService.createUser(userDto);
        returnValue = modelMapper.map(createdUser, UserResponse.class);

        return userResponse;
    }

我的userresponse类看起来像

public class UserRest {

    private String userId;
    private String firstName;
    private String lastName;
    private String email;
    ....getters and setters

这个流程运行良好。但现在我需要向createuser方法(jsr303)添加验证,以检查传入的json字段是否正常。为此,我试图添加以下代码在我的控制器

@PostMapping
    public UserResponse createUser(@Valid @RequestBody UserDetailsRequestModel userDetails, BindingResult result){

        if(result.hasErrors()){
            Map<String, String> errorMap = new HashMap<>();

            for(FieldError error: result.getFieldErrors()){
                errorMap.put(error.getField(), error.getDefaultMessage());
            }
          **return new ResponseEntity<Map<String, String>>(errorMap, HttpStatus.BAD_REQUEST);**
        }

        UserRest userResponse= new UserRest();

        ModelMapper modelMapper = new ModelMapper();
        UserDto userDto = modelMapper.map(userDetails, UserDto.class);
        userDto.setRoles(new HashSet<>(Arrays.asList(Roles.ROLE_USER.name())));
        UserDto createdUser = userService.createUser(userDto);
        returnValue = modelMapper.map(createdUser, UserResponse.class);

        return**userResponse**;

我的代码中明显的问题是无法将responseentity<map<string,string>>转换为userresponse对象。
有合适的方法吗?这样我就可以发送错误(如果有的话)或者userresponse对象(如果在同一个控制器方法中没有错误的话)?

20jt8wwn

20jt8wwn1#

返回响应类型<?>

@PostMapping
public ResponseEntity<?> createUser(@Valid @RequestBody UserDetailsRequestModel userDetails, BindingResult result){
    if(result.hasErrors()){
        ...
        return ResponseEntity.badRequest().body(errorMap);
    }
    ...
    return ResponseEntity.ok(userRequest);
}
hsgswve4

hsgswve42#

您可以从接受这两种响应类型的控制器方法返回httpentity<?>泛型对象。必须将userresponse包在responseentity对象周围

相关问题