HTTP return error from RESTeasy interface

Is it possible to return an HTTP error from the RESTeasy interface? I am currently using anchored web filters for this, but I want to know if this is possible right 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; } } } 
+7
source share
3 answers

Found a solution, and it is 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); } } } 
+19
source

You can also use java exceptions in your method and then provide javax.ws.rs.ext.ExceptionMapper to match the Http error. The following blog contains more detailed information, especially step number 2:

http://www.sivalabs.in/2012/06/resteasy-tutorial-part-3-exception.html

+2
source

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

This will save you from stacktrace related exception.

0
source

All Articles