0

I have a REST endpoint that has a request parameter “myParam”. This is a required parameter without which any GET request made to this endpoint is considered a bad request. I’m using Swagger to highlight the fact that this parameter is required, as follows

@ApiParam(required = true) @RequestParam(value = "myParam") String myParam

The problem is that when I submit a GET to this endpoint via Postman the HTTP error returned is a 500 saying that the required parameter myParam is not provided. Is there any way to refactor this so that if a parameter labelled by Swagger as required is missing the response is 404 instead?

Space Cadet
  • 385
  • 6
  • 23

1 Answers1

1

A solution could be creating a class and annotate it with @ControllerAdvice. This class' methods are responsible for handling specific exception passed as parameters. In your 500 error there should be an exception stack trace like "Caused by .. org.somepackage.SomeException ...".

1) You can create a custom class which contains a message and a HttpStatus code:

public class ExceptionResponse {
  private HttpStatus httpStatus;
  private String errorMessage;
  //getters;setters;
}

2) The @ControllerAdvice annotated class should look like this :

@ControllerAdvice
public class RestExceptionHandler {

@ExceptionHandler(value = SomeException.class)
public ResponseEntity<ExceptionResponse> handleMissingRequiredParameters(SomeException ex) {
    ExceptionResponse exceptionResponse = new ExceptionResponse();
    exceptionResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
    exceptionResponse.setErrorMessage(ex.getMessage());
    return new ResponseEntity<>(exceptionResponse, exceptionResponse.getHttpStatus());
}
}

And now, when the SomeException is thrown, the actual response that you'll see is an ExceptionResponse JSON with a custom httpStatus and errorMessage.

user1234SI.
  • 1,812
  • 1
  • 8
  • 22