I am using spring boot for creating rest services. I need to validate the parameter passed. I have a service like below,
@GetMapping(value="/employee/{Id}")
public EmployeeDTO getEmployeeDetails(@PathVariable String Id) {
...
}
I need to throw error if Id is not passed in url. Like "Missing Id in request". I was able to achieve using below,
@GetMapping(value={"/employee", "/employee/{Id}"})
public EmployeeDTO getEmployeeDetails(@PathVariable String Id) {
...
}
And handled MissingPathVariableException in ExceptionHandler annotated with @ControllerAdvise.
But I wanted to know is this the right way to check ?
You can use
@ControllerAdvise
to handle exceptions that are generated while executing your actual code.For Path variable validation, you can make use of
spring-boot-starter-validation
.Add this maven dependency:
Then your controller will look like:
I recommend you to read this: Validating Form Input