Return list of errors

2019-07-25 08:47发布

I wan to return a list of errors using this Response object:

public class StringResponseDTO {

    private String response;

    public StringResponseDTO(String response) {
        super();
        this.response = response;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}

I use this code to generate errors:

List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors ) {
          System.out.println ("Validation error in field: " + error.getObjectName() 
                          + "! Validation error message: " + error.getDefaultMessage() 
                          + "! Rejected value:" + error.getRejectedValue());
          return ResponseEntity.ok(new StringResponseDTO(error.getField() + " " + error.getDefaultMessage()));
        }

I want to return a list like this:

response: {
   errors: [
      field_name: message,
      second_name: second_message
           ]
}

Do you know how I can modify the code? Probably I need add constructor?

1条回答
不美不萌又怎样
2楼-- · 2019-07-25 09:53
response: {
   errors: [
      field_name: message,
      second_name: second_message
           ]
}

You need to use the following classes to model the above json:

@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
@JsonTypeName("response")
class StringResponseDTO {

    private List<String> errors;

    public StringResponseDTO(final List<String> errors) {
        this.errors = errors;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(final List<String> errors) {
        this.errors = errors;
    }
}

You can construct the response as:

List<String> errorsList = new ArrayList<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
     System.out.println ("Validation error in field: " + error.getObjectName() 
                     + "! Validation error message: " + error.getDefaultMessage() 
                     + "! Rejected value:" + error.getRejectedValue());
          errorsList.add(error.getField() + " " + error.getDefaultMessage());
}

return ResponseEntity.badRequest().body(new StringResponseDTO(errorsList));
查看更多
登录 后发表回答