2012-03-14 13 views
6

È possibile restituire un errore HTTP da un'interfaccia RESTeasy? Attualmente sto usando web-filtri incatenati per questo, ma voglio sapere se è possibile direttamente dalla interfaccia ...Restituisce errore HTTP dall'interfaccia RESTeasy

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

risposta

18

trovato la soluzione ed è molto semplice:

throw new WebApplicationException(); 

Quindi:

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

Return un javax.ws.rs.core.Response per impostare il codice di risposta.

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

che vi farà risparmiare lo stacktrace associato con un'eccezione.