我想抓住
WebApplicationException
javax.ws.rs.ext.ExceptionMapper
@GET
@Path("/saySomething")
public List<String> saySomething() {
String response = EchoRestClient.ping();
List<String> list = new ArrayList<>();
list.add(response);
list.add("okay");
return list;
}
(1)这是调用另一个rest api的客户端类:
public class EchoRestClient {
private static Client client = ClientBuilder.newClient();
public static String ping() {
String serviceUrl = PropertyReader.getProperty(ServiceUrl.ECHO_SERVICE);
Response response = client
.target(serviceUrl)
.path("saySomething")
.request(ExtendedMediaType.APPLICATION_UTF8)
.get();
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
return response.getEntity(String.class);
}
throw new WebApplicationException(response);
}
}
以及我的自定义异常处理程序,它不捕捉上述抛出的异常:
@Provider
public class WebservletExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception exception) {
System.out.println("caught exception");
Response response;
if (exception instanceof WebApplicationException) {
response = ((WebApplicationException) exception).getResponse();
} else {
response = Response....build();
}
return response;
}
}
public static String ping() {
// same code then before
WebApplicationException e = new WebApplicationException(response);
throw new RuntimeException("xxxxxx", e);
}
我上面的代码运行良好,当我调用
saySomething
我的web浏览器中的rest方法。
EchoService
rest(包含被调用的
ping
rest方法)HTTP 404在第一种情况下未被捕获。我需要抛出RuntimeException,因为未捕获WebApplicationException(第二种情况)。
这里怎么了?
如果我抛出此异常,则可以捕获:
throw new WebApplicationException(response.getStatus())
但这一点不起作用:
throw new WebApplicationException(response)