Saveendra Ekanayake Saveendra Ekanayake - 4 months ago 50
Java Question

How to return different types of ResponseEntity in Spring MVC

I have written simple rest application using Spring MVC 4. Within the controller I have return

ResponseEntity
. But in some cases I want to give success JSON and if there is validation error I want to give error JSON. Currently success and error responses are totally different, So I have created 2 classes for error and success. Within the controller I want to return
ResponseEntity<Success>
, if the internal logic is okay. Otherwise I want to return
ResponseEntity<Error>
. Is there any way to do it.

Success
and
Error
are the 2 classes that i use to represent success and error response.

Answer

Its possible to return ResponseEntity without using generics, such as follows,

public ResponseEntity method() {
    boolean isValid = // some logic
    if (isValid){
        return new ResponseEntity(new Success(), HttpStatus.OK);
    }
    else{
        return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST);
    }
}
Comments