简体   繁体   中英

Java return ResponseEntity of two different types

Trying to return a bad request error code in a catch block, otherwise returning a collection. Not sure how to set the method return type to handle both.

Rough pseudo code:

public ResponseEntity</*what goes here*/> getCollection() {
    try {
        return ResponseEntity.ok().body(someCollection);
    } catch(SomeException e) {
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    }
}

Is my approach incorrect to simply assume I can just set a generic type to handle both return types?

Use javax.ws.rs.core.Response as return type. entity can be JSON object

ResponseBuilder rb = Response.ok(entity);
return rb.build();

Same way you can build entity JSON in catch block with proper error msg.

OR

Create custom class by extending javax.ws.rs.WebApplicationException .

In your case, I would do this:

public ResponseEntity<Object> getCollection() { // -> "Object is added between "<>"
    try {
        return ResponseEntity.ok().body(someCollection);
    } catch(SomeException e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST); // -> "String" is removed between "<>"
    }
}

Object is a parent class of all classes and Java has the ability to infer types. Because of that ability body(someCollection) will be returned as ResponseEntity<Object> type and new ResponseEntity<>(HttpStatus.BAD_REQUEST) also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM