8

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;
        }
    }
}
travega
  • 8,284
  • 16
  • 63
  • 91

3 Answers3

22

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);
        }
    }
}
travega
  • 8,284
  • 16
  • 63
  • 91
2

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. The following blog has more details, particularly step #2:

https://www.javacodegeeks.com/2012/06/resteasy-tutorial-part-3-exception.html

homaxto
  • 5,428
  • 8
  • 37
  • 53
2

Return a javax.ws.rs.core.Response to set the response code.

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.

flob
  • 3,760
  • 2
  • 34
  • 57