[英]Return HTTP error from RESTeasy interface
Is it possible to return a HTTP error from a RESTeasy interface? 是否可以从RESTeasy接口返回HTTP错误? I am currently using chained web-filters for this but I want to know if it is possible straight from the interface...
我目前正在使用链式网络过滤器,但我想知道是否可以直接从界面...
Example sudo-code: 示例sudo-code:
@Path("/foo")
public class FooBar {
@GET
@Path("/bar")
@Produces("application/json")
public Object testMethod(@HeaderParam("var_1") @DefaultValue("") String var1,
@HeaderParam("var_2") @DefaultValue("") String var2 {
if (var1.equals(var2)) {
return "All Good";
} else {
return HTTP error 403;
}
}
}
Found the solution and it's very simple: 找到解决方案,它非常简单:
throw new WebApplicationException();
So: 所以:
@Path("/foo")
public class FooBar {
@GET
@Path("/bar")
@Produces("application/json")
public Object testMethod(@HeaderParam("var_1") @DefaultValue("") String var1,
@HeaderParam("var_2") @DefaultValue("") String var2 {
if (var1.equals(var2)) {
return "All Good";
} else {
throw new WebApplicationException(HttpURLConnection.HTTP_FORBIDDEN);
}
}
}
You can also throw java exceptions within your method and then provide an javax.ws.rs.ext.ExceptionMapper
to map that to an Http error. 您还可以在方法中抛出java异常,然后提供
javax.ws.rs.ext.ExceptionMapper
以将其映射到Http错误。 The following blog has more details, particularly step #2: 以下博客有更多细节,特别是第2步:
https://www.javacodegeeks.com/2012/06/resteasy-tutorial-part-3-exception.html https://www.javacodegeeks.com/2012/06/resteasy-tutorial-part-3-exception.html
Return a javax.ws.rs.core.Response
to set the response code. 返回
javax.ws.rs.core.Response
以设置响应代码。
import javax.ws.rs.core.Response;
@Path("/foo")
public class FooBar {
@GET
@Path("/bar")
@Produces("application/json")
public Response testMethod(@HeaderParam("var_1") @DefaultValue("") String var1,
@HeaderParam("var_2") @DefaultValue("") String var2 {
if (var1.equals(var2)) {
return Response.ok("All Good").build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Sorry").build()
}
}
}
That will save you the stacktrace associated with an exception. 这将为您节省与异常相关的堆栈跟踪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.