Return HTTP error from RESTeasy interface

travega picture travega · Mar 14, 2012 · Viewed 9.1k times · Source

Is it possible to return a HTTP error from a RESTeasy interface? 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:

@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;
        }
    }
}

Answer

travega picture travega · Mar 14, 2012

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);
        }
    }
}