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

Can i send a error-map along with a response object in response? What is the proper way?

我有一个 spring 休息端点,它接受一个用户对象和 returns 另一个用户对象作为响应。我的控制器方法如下所示:

@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;
    }

我的用户响应class看起来像

public class UserRest {

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

这个流程运行良好。但现在我需要向 createUser 方法 (JSR 303) 添加验证以检查传入的 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> 转换为 UserResponse 对象。

有正确的方法吗?这样我就可以发送错误(如果有)或 UserResponse 对象(如果同一控制器方法中没有错误)?

您可以 return 来自接受两种响应类型的控制器方法的 HttpEntity 通用对象。 您必须将 UserResponse 响应包装在 ResponseEntity 对象周围

Return 一种 ResponseEntity

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