0

For the Page Number if someone has entered "test" , I want to customise the error message "Please provide the correct type for the parameter : pageNo".

Request Object:

 {
        "pageSize":6,
        "pageNo":"test",
        "sortBy": "lastModifiedTime"
    }

How do i determine the the parameter which caused the exception :

@ExceptionHandler({ HttpMessageNotReadableException.class, HttpMediaTypeNotSupportedException.class,
            HttpMessageNotWritableException.class,
            ConversionNotSupportedException.class })
    public ResponseEntity<RestResponse> handleRequestErrors(final Exception ex) {
        RestResponse response = new RestResponse();
        response.setCode(HttpStatus.BAD_REQUEST.value());
        response.setStatus(false);
        response.setMsg(ex.getMessage());
        if (ex instanceof HttpMediaTypeNotSupportedException 
                || ex instanceof HttpMessageNotWritableException
                || ex instanceof HttpMessageNotReadableException) {
            response.setMsgCode(AppCode.E_GEN_CONTENT_TYPE_NOT_SUPPORTED);
        }
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

The same scenario can be handled for the query param validation :

Controller Advice :

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public ResponseEntity<RestResponse> handleMethodArgumentTypeMismatchException(HttpServletRequest request,
            MethodArgumentTypeMismatchException exception) {
        RestResponse response = new RestResponse();
        response.setCode(HttpStatus.BAD_REQUEST.value()); // 400
        response.setStatus(false);
        response.setMsgCode(AppStrings.BAD_REQUEST);
        String param = exception.getName();
        response.setMsg("Please provide the correct type for the parameter : " + param);
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

Controller Class :

    public ResponseEntity<RestResponse> getNotifications(
                @RequestParam(defaultValue = "0") @Min(0) IntegerpageNo,
@RequestParam(defaultValue = "5") @Min(1) Integer pageSize,
@RequestParam(defaultValue = "lastModifiedTime") String sortBy) {
Karthik Suresh
  • 367
  • 7
  • 23
  • Should this value not be tested at the endpoint? You can throw custom error message there. – Prashant Nov 11 '19 at 13:05
  • What do `getRootCause` and `getMostSpecificCause` say on those exceptions? It's possible that there are nested exceptions with info you want. – M. Prokhorov Nov 11 '19 at 13:12

0 Answers0