Return list of errors

丶灬走出姿态 提交于 2019-12-11 07:33:16

问题


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:


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));


来源:https://stackoverflow.com/questions/55445649/return-list-of-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!