我目前正在使用Restlets框架,我找不到在服务方法中手动设置HTTP响应代码的方法。请考虑以下代码片段:
public class MyResource extends ServerResource {
@Post("json")
public Representation doSomething(Representation entity) throws IOException {
int status = 200;
try {
// do something which might throw an exception
}
catch (Exception e) {
// log the exception
// *** I would like to assign HTTP status 500 here ***
status = 500;
}
JSONObject responseJSON = new JSONObject();
responseJSON.put("result", "some data");
Representation rep = new JsonRepresentation(responseJSON.toJSONString());
return rep;
}
}
我有能力捕获并记录异常,如果发生异常,但我不清楚如何更改HTTP响应代码。据我所知,从doSomething
返回将由具有200 HTTP响应代码的Restlet自动处理。
我知道如何直接从过滤器或servlet分配状态代码,但是是否可以在Restlets中执行此操作,而无需进入servlet层?
答案 0 :(得分:0)
据我所知,有一个名为ResponseEntity的对象,您可以使用它来操作微服务和请求 - 响应编程模型,它允许您指定返回的HTTP返回码。但是,您需要实体,我认为这低于您的Servlet抽象级别。
您可以将它们更改为某些预定义的值,例如HTTP.INTERNAL_SERVER_ERROR等,这些值会转换为最终的值,最后您可以使用Google。
我希望这有一些帮助
编辑:
导入ResponseEntity对象的必要资源。在STS中,它是
import org.springframework.http.ReponseEntity;
import org.springframework.http.HttpStatus;
public class MyResource extends ServerResource {
@Post("json")
public ResponseEntity<Representation> doSomething(Representation entity) throws IOException {
int status = 200;
try {
// do something which might throw an exception
}
catch (Exception e) {
ResponseEntity<Representation> response = null;
response = new ResponseEntity<Representation>(HttpStatus.INTERNAL_SERVER_ERROR);
return response;
}
JSONObject responseJSON = new JSONObject();
responseJSON.put("result", "some data");
Representation rep = new JsonRepresentation(responseJSON.toJSONString());
return rep;
}
抱歉延误。我是Stack Overflow的新手