Reputation: 39
I am creating an controller where there is certain attributes in json which is an doing in postman a POST request like this if all attributes are posted then its fine
if one then is missing then it would look like this
i want this response when some attribute is missing how to implement this
Upvotes: 1
Views: 293
Reputation: 44942
This is normally implemented in two steps:
Implement a validation mechanism for the method that handles the incoming request. Normally you would throw an exception here if the input is incorrect, in your example a missing JSON key.
Implement a global error handler that will process the exception from point 1 and format the response as JSON.
For point 1 the usual choice is the Java Bean Validation framework because it's integrated with Spring Boot and allows to define validation constraints with annotations like @NotEmpty
. You can take a look at this example.
For point 2 the usual choice is @RestControllerAdvice
or @ControllerAdvice
. You would have to understand your service web server setup to implement it properly e.g. it might behave differently if you use Spring WebFlux.
Upvotes: 1