Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Spring send 422 in response when input Id is string

I have a Rest controller and in my controller I have method for showing single user record. consider url is like this :

/api/v1/users/{id}

and this is my method


    @GetMapping("/{id}")
    @Operation(summary = "Show single user", security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Found the User", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }),
            @ApiResponse(responseCode = "404", description = "User not found", content = @Content)
    })
    public UserDto getUserById(@PathVariable Long id) throws ResourceNotFoundException {
        return modelMapper.map(userService.findUserById(id), UserDto.class);
    }

The problem is when I send "/api/v1/users/some-string" then I get 500, how can I handle this and return 422 with message of invalid user id ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should declare @ExceptionHandler method for MethodArgumentTypeMismatchException in your controller or in separate class annotated @ControllerAdvice or @RestControllerAdvice, for example so:

    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    ApiError handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        // construct ApiError
        // return ApiError
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading