How to change the controller response in the filter so that the response structure is consistent throughout the API using spring-boot

I applied the REST API using the spring-boot application. All my APIs now return a JSON response for each object. This answer was used by another server, which expects all of these answers to be in the same JSON format. For instance:

All my answers should be placed in the following structure:

public class ResponseDto { private Object data; private int statusCode; private String error; private String message; } 

Spring-boot is currently returning error responses in a different format. How to achieve this using a filter.

Error message format;

 { "timestamp" : 1426615606, "exception" : "org.springframework.web.bind.MissingServletRequestParameterException", "status" : 400, "error" : "Bad Request", "path" : "/welcome", "message" : "Required String parameter 'name' is not present" } 

I need both the error and the successful response are in the same json structure in my entire spring-boot application

+5
source share
1 answer

This can be achieved simply by using the ControllerAdvice and handling all possible exceptions, and then returning the response of your choice.

 @RestControllerAdvice class GlobalControllerExceptionHandler { @ResponseStatus(HttpStatus.OK) @ExceptionHandler(Throwable.class) public ResponseDto handleThrowable(Throwable throwable) { // can get details from throwable parameter // build and return your own response for all error cases. } // also you can add other handle methods and return // `ResponseDto` with different values in a similar fashion // for example you can have your own exceptions, and you'd like to have different status code for them @ResponseStatus(HttpStatus.OK) @ExceptionHandler(CustomNotFoundException.class) public ResponseDto handleCustomNotFoundException(CustomNotFoundException exception) { // can build a "ResponseDto" with 404 status code for custom "not found exception" } } 

Some great read on controller controller controllers

+3
source

Source: https://habr.com/ru/post/1266033/


All Articles