两种不同类型的Java返回响应
试图在catch块中返回错误的请求错误代码,否则返回集合。不确定如何设置方法返回类型来处理这两种情况 粗略的伪代码:两种不同类型的Java返回响应,java,rest,Java,Rest,试图在catch块中返回错误的请求错误代码,否则返回集合。不确定如何设置方法返回类型来处理这两种情况 粗略的伪代码: public ResponseEntity</*what goes here*/> getCollection() { try { return ResponseEntity.ok().body(someCollection); } catch(SomeException e) { return new Response
public ResponseEntity</*what goes here*/> getCollection() {
try {
return ResponseEntity.ok().body(someCollection);
} catch(SomeException e) {
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
}
}
public ResponseEntity getCollection(){
试一试{
返回ResponseEntity.ok().body(someCollection);
}捕获(某些例外){
返回新的响应属性(HttpStatus.BAD_请求);
}
}
简单地假设我可以设置一个泛型类型来处理这两种返回类型,这是不正确的吗?使用
javax.ws.rs.core.Response
作为返回类型。实体可以是JSON对象
ResponseBuilder rb = Response.ok(entity);
return rb.build();
同样,您可以在catch块中使用正确的错误消息构建实体JSON
或
通过扩展javax.ws.rs.WebApplicationException
使用javax.ws.rs.core.Response
作为返回类型来创建自定义类。实体
可以是JSON对象
ResponseBuilder rb = Response.ok(entity);
return rb.build();
同样,您可以在catch块中使用正确的错误消息构建实体JSON
或
通过扩展javax.ws.rs.WebApplicationException
创建自定义类在您的情况下,我会这样做:
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 "<>"
}
}
public ResponseEntity getCollection(){/->“对象添加到”
试一试{
返回ResponseEntity.ok().body(someCollection);
}捕获(某些例外){
return new ResponseEntity(HttpStatus.BAD_请求);//->“字符串”在“”之间被删除
}
}
Object
是所有类的父类,Java具有推断类型的能力。由于该能力,body(someCollection)
将作为ResponseEntity
类型和newresponseEntity(HttpStatus.BAD_REQUEST)
返回。在您的情况下,我会这样做:
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 "<>"
}
}
public ResponseEntity getCollection(){/->“对象添加到”
试一试{
返回ResponseEntity.ok().body(someCollection);
}捕获(某些例外){
return new ResponseEntity(HttpStatus.BAD_请求);//->“字符串”在“”之间被删除
}
}
Object
是所有类的父类,Java能够推断类型。由于该功能,body(someCollection)
将作为ResponseEntity
类型和新ResponseEntity(HttpStatus.BAD_REQUEST)
返回。为什么不能像public ResponseEntity getCollection()那样给出
@TomSebastian以某种方式触发了一个不兼容的类型错误:SMy错误您应该给出public ResponseEntity getCollection()
为什么不能像public ResponseEntity getCollection()那样给出
@TomSebastian以某种方式触发了一个不兼容的类型错误:SMy错误您应该给出public ResponseEntity getCollection()
如果我坚持使用ResponseEntity作为返回类型怎么办?如果我坚持使用ResponseEntity作为返回类型怎么办?