简体   繁体   中英

Spring boot API custom error response contract

I'm trying to build a TODO application with Java Spring boot. Added a validation at the controller layer to make sure my todo name length is between 2 and 10 for the create API. I've configured to return the following response for the success:

{
  "success": true,
  "data": {"name": "hello", "completed": false},
  "errors": []
}

I would like to return the same contract in failure case as well. But when I try to make a failing request (with name greater than 10 chars), the server is returning the following response somehow.

{
"timestamp": "2019-11-21T15:41:28.545+0000",
"status": 400,
"error": "Bad Request",
"errors": [
    {
        "codes": [
            "Size.createTodoContract.name",
            "Size.name",
            "Size.java.lang.String",
            "Size"
        ],
        "arguments": [
            {
                "codes": [
                    "createTodoContract.name",
                    "name"
                ],
                "arguments": null,
                "defaultMessage": "name",
                "code": "name"
            },
            10,
            2
        ],
        "defaultMessage": "size must be between 2 and 10",
        "objectName": "createTodoContract",
        "field": "name",
        "rejectedValue": "attend wedding",
        "bindingFailure": false,
        "code": "Size"
    }
],
"message": "Validation failed for object='createTodoContract'. Error count: 1",
"path": "/api/todos"
}

My payload validation is as follows:

@Getter
public class CreateTodoContract {
  @Size(min = 2, max = 10)
  private String name;

  @NotNull
  private boolean completed;
}

Please help me to understand where am I supposed to update the actual contract for failure cases?

You have messed up some coding parts in your project.

1) First of all, add “message” attribute for all @Size annotation and all other annotations which are related with validations (@NotNull, @NotEmpty etc.). When you try to make failure request, API wil be returning error message which you have mentioned in the “message” attribute. See the below code lines. Use javax.validation.constraints library for these annotations. Others also okay. But this is much better.

@Size(min = 1, message = "email can not be empty")
@NotNull(message = "email can not be null")
private String email;

2) Then you should catch these invalid scenarios in the controller (API definition) like below by using “BindingResult” class (org.springframework.validation). As well as you should use @Valid annotaion for you request body (CreateTodoContract) Otherwise server is retuning response for the invalid scenarios which you have mentioned in the question.

@PostMapping(value = "createTodoContract")
public ResponseEntity<Object> CreateTodoContract(@Valid @RequestBody 
                                                 CreateTodoContract 
                                                 createTodoContractRequest,
                                                 BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        String error = bindingResult.getAllErrors().get(0).getDefaultMessage();
        return new ResponseEntity<>(responseBuilder.build("02", error), status);
    }

    return new ResponseEntity<>(response, response.getStatus());

}

String error = bindingResult.getAllErrors().get(0).getDefaultMessage()

You can get error message by using above code line.

If your API request have more than one request parameters to be validated, please use below mentioned code line for catching error messages. Otherwise API is getting different error messages which you have mentioned in the code base time to time (sporadic issue)

if (bindingResult.hasErrors()) {
        String error = bindingResult.getAllErrors().get(0).getDefaultMessage();

        if (bindingResult.getAllErrors().size() == 1) {
            return new ResponseEntity<>(responseBuilder.build("02", error), status);

        } else {
            return new ResponseEntity<>(
                    responseBuilder.build("02", "mandatory parameters can not be 
            empty, null or invalid"), status);

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM