Issue
I create an application in Spring Boot. And I want to know which one is good for following situation.
I have a rest endpoint, and user send an id
as a path variable, then I want to check that id
is null or not, if it is null,
Which choice is good for handling this sitatution?
Choice 1
if(id == null || id < 0) {
throw new BadRequestException("Id cannot be null");
}
Create a new Exception called BadRequestException
, then handle it on the General Exception Handler Controller
or
Choice 2
Return a custom object contains (status, message, details ...)
Here is the whole method
@GetMapping("/user/{id}")
public UserResponseVM getIndividualUser(@PathVariable("id") Long id) {
if(id == null || id < 0) {
throw new BadRequestException("Id cannot be null");
}
// I got stuck in here therefore method isn't completed
return null;
}
Solution
Definitely option 1, except that you don't have to handle it in the global exception handler if you annotate the exception class with ResponseStatus in the following way:
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
class BadRequestException extends RuntimeException {}
Answered By - birca123
Answer Checked By - Candace Johnson (JavaFixing Volunteer)