RESTEasy Client Exception Handling

I have a simple client using RESTEasy as follows:

public class Test { public static void main(String[] args) { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target("http://localhost"); client.register(new MyMapper()); MyProxy proxy = target.proxy(MyProxy.class); String r = proxy.getTest(); } } public interface MyProxy { @GET @Path("test") String getTest(); } @Provider public class MyMapper implements ClientExceptionMapper<BadRequestException>{ @Override public RuntimeException toException(BadRequestException arg0) { // TODO Auto-generated method stub System.out.println("mapped a bad request exception"); return null; } } 

The server is configured to return 400 - Bad Request to http://localhost/test along with a useful message. A BadRequestException thrown by ClientProxy . Besides wrapping in try/catch , how can I make getTest() catch an exception and return a useful Response message as a string. I tried various implementations of ClientExceptionMapper , but it just might seem like everything is correct. The above code never throws a toException . What am I missing here?

My current job uses ClientResponseFilter , and then run setStatus(200) and enter the initial status in the response object. This way I avoid the exception.

+10
java jax-rs resteasy
source share
2 answers

ClientExceptionMapper in Resteasy is deprecated (see Java docs )

The JAX-RS 2.0 client proxy platform in the resteasy-client module does not use org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper.

Try using ExceptionMapper as follows:

 import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class MyMapper implements ExceptionMapper<ClientErrorException> { @Override public Response toResponse(ClientErrorException e) { return Response.fromResponse(e.getResponse()).entity(e.getMessage()).build(); } } 

Yours faithfully,

0
source share

I would suggest using the Jax-RS API if you don't need functionality with RestEasy clients. (RestEasy ships with Jax-RS, so there are no differences in the library)

 Client client = ClientFactory.newClient(); WebTarget target = client.target("http://localhost/test"); Response response = target.request().get(); if ( response.getStatusCode() != Response.Status.OK.getStatusCode() ) { System.out.println( response.readEntity(String.class) ); return null; } String value = response.readEntity(String.class); response.close(); 

The reason your mapper does not work is because the client is not actually throwing an exception. The client returns the actual result to the proxy, and the proxy reads this and throws an exception that occurs after it can catch it.

-one
source share

All Articles