user1523271
user1523271

Reputation: 1063

Spring missing query parameters exception handling

I have this code:

@GetMapping(value = "/users/{id}")
@ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( @PathParam("id")  @PathVariable("id") @RequestParam Long id) {
    return adminService.getUserById(id);
}

and this code:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
        public ResponseEntity<Object> handleHttpMessageNotReadable(
                HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
            return error_with_my_info;
    }

    @Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
        MissingServletRequestParameterException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {{
        return error_with_my_info;
    }
...
}

The problem is that when I send a request WITHOUT a parameter, it is handleHttpMessageNotReadable that is called, not handleMissingServletRequestParameter. Why is that? Can other API endpoints affect this behaviour, like having a PUT request handler with the same endpoint? How can I make it so that handleMissingServletRequestParameter?

Upvotes: 0

Views: 1646

Answers (1)

Divanshu Aggarwal
Divanshu Aggarwal

Reputation: 446

Improvised :

@GetMapping(value = "/users")
@ResponseStatus(HttpStatus.OK)
public DtoUser getUserById(  @RequestParam(value="id" , required=true)Long id) {
    return adminService.getUserById(id);
}

localhost:8080?id=test now if you dont pass id it will give you handleMissingServletRequestParameter.

Upvotes: 1

Related Questions