0

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 ?

0

1 Answer 1

2

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
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.