I have implemented REST API using spring-boot application. All my API's are now returning response in JSON format for each entity. This response was consumed by other server which expects all these response are in same JSON format. For example;
All my responses should be accommodated within the following structure;
public class ResponseDto {
private Object data;
private int statusCode;
private String error;
private String message;
}
Currently spring-boot returns error responses in a different format. How to achieve this using 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 error and successfull response are in same json structure all over my spring-boot application
This can be achieved simply by utilizing a ControllerAdvice and handling all possible exceptions, then returning a response of your own choosing.
@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 advice exception handlers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With