从RESTeasy界面返回HTTP错误

tra*_*ega 7 java http httpresponse resteasy http-response-codes

是否可以从RESTeasy接口返回HTTP错误?我目前正在使用链式网络过滤器,但我想知道是否可以直接从界面...

示例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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

tra*_*ega 20

找到解决方案,它非常简单:

throw new WebApplicationException();
Run Code Online (Sandbox Code Playgroud)

所以:

@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)