Java返回两种不同类型的ResponseEntity

时间:2015-12-23 03:20:05

标签: java rest

尝试在catch块中返回错误的请求错误代码,否则返回一个集合。不知道如何设置方法返回类型来处理两者。

粗伪代码:

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

我的方法是不正确的,只是假设我可以设置一个泛型类型来处理两种返回类型?

2 个答案:

答案 0 :(得分:0)

使用javax.ws.rs.core.Response作为返回类型。entity可以是JSON对象

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

您可以使用正确的错误信息在catch块中构建实体JSON。

通过扩展javax.ws.rs.WebApplicationException来创建自定义类。

答案 1 :(得分:0)

在您的情况下,我会这样做:

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是所有类的父类,并且Java能够推断类型。由于这种能力,body(someCollection)将以ResponseEntity<Object>类型返回,new ResponseEntity<>(HttpStatus.BAD_REQUEST)也将返回。