Skip to content
Advertisement

Throwing custom errors as Json when a parameter is invalid

I am working on an API and need to throw and exception that looks like this

"error": "sortBy parameter is invalid"
}

if the sort by parameter is not one of my predetermined values, i have a few parameters to do this for here is what my controller looks like

@GetMapping("/api/posts")

    public ResponseEntity<List<Post>> getPostResponse(@RequestParam String tag, Optional<String> sortBy,
            Optional<String> direction) throws InvalidSortBy {

        RestTemplate postResponseTemplate = new RestTemplate();
        URI postUri = UriComponentsBuilder.fromHttpUrl("urlHere")
                                          .queryParam("tag", tag)
                                          .queryParamIfPresent("sortBy", sortBy)
                                          .queryParamIfPresent("direction", direction)
                                          .build()
                                          .toUri();

        ResponseEntity<PostResponse> response = postResponseTemplate.getForEntity(postUri, PostResponse.class);
        ResponseEntity<List<Post>> newResponse = responseService.createResponse(response, sortBy, direction);   
    
         return newResponse;

    }
}

ive remove the url but it works for sorting the incoming data but i need to validate and throw correct errors, im just really not sure how to do it in the format required, as json, any help appreciated

Advertisement

Answer

First you need to handle your exception and resolve it based on error, I would suggest you raise error codes for known application exception and resolve them in your exception handler (either by using @ControllerAdvice or @RestControllerAdvice), once you have translated error code to respective message send them as json you can refer below thread for more details on following SO thread

How to throw an exception back in JSON in Spring Boot

@ExceptionHandler

@ExceptionHandler to tell Spring which of our methods should be invoked for a given exception

@RestControllerAdvice

Using @RestControllerAdvice which contains @ControllerAdvice to register the surrounding class as something each @Controller should be aware of, and @ResponseBody to tell Spring to render that method’s response as JSON

Advertisement