Setting error message for an incomplete object passed through postman

Viewed 261

Suppose I am sending a complete JSON object in Postman like the below one for POST-end-point:

{
"student": [
    {
        "studentId" : "1234",
        "feesPayment" : {
            "amount" : 500.0,
            "code" : "INR"
        }
    },
    {
        "studentId" : "5678",
        "feesPayment" : {
            "amount" : 500.0,
            "code" : "INR"
        }
    }
]

}

then the status code is 200 OK

But now, I am sending the same JSON object but with some modification in the object like the below one for the same POST-end-point: (just removing the "feesPayment" object)

{
    "student": [
        {
            "studentId" : "1234"
        },
        {
            "studentId" : "5678"
        }
    ]
}

then the status code is 500 Internal Server Error for obvious reasons and the error looks like the below one:

{
    "timestamp" : "2021-09-02T17:07:31",
    "status" : 500,
    "error" : "Internal Server Error",
    "message" : "Internal Server Error"
}

For this 500 status code, the error message is "Internal Server Error". So my question is How can I set this error message to something else like "Fee Payment Details are missing" instead of the default Internal Server Error message?

Approach/Code in Java and SpringBoot is appreciated.

1 Answers

Please look into

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

In your Student class, then you can write something like:

public class Student {
   @NotNull(message = "Error-2596-Fees Payment is required")
   private FeesPayment feesPayment;
}

In the RestController, you will send in Student payload with @Valid annotation

  public ResponseEntity<String> sendStudent(@Valid Student studentToSend) { }

The messages have to be constants. If you look at the code of the annotation, you will see it reads

javax.validation.constraints.NotBlank.message

As the default value. You could support internationalization and create a language properties file then define it like:

javax.validation.constraints.NotBlank.message = "Payment is required" 

Another thing to consider, is perhaps you wish to combine many errors and return them to the user at once.

For such a case look into ExceptionHandler:

@RestControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler{

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String, Object> responseBody = new LinkedHashMap<>();

        List<String> allErrors = new ArrayList<>();
        ex.getBindingResult().getAllErrors().forEach(error -> allErrors.add(error.getDefaultMessage()));
        responseBody.put("Errors:", allErrors);

        return new ResponseEntity<>(responseBody, headers, status);
    }
}
Related