问题
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;
}
}
}
回答1:
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);
}
}
}
回答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
回答3:
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.
来源:https://stackoverflow.com/questions/9694169/return-http-error-from-resteasy-interface