Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change controller response in filter to make the response structure consistent all over the API's using spring-boot

Tags:

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

like image 856
Achaius Avatar asked Mar 28 '17 18:03

Achaius


1 Answers

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

like image 172
buræquete Avatar answered Oct 11 '22 14:10

buræquete