我正在尝试在Web服务上进行一些自定义错误处理。在我的Web服务中,我创建了一个自定义Exception类,扩展了WebApplicationException,如JAX-RS / Jersey how to customize error handling?中所述:
public class InternalServerErrorException extends WebApplicationException {
public InternalServerErrorException(String message) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.header("errorMessage", message).type(MediaType.TEXT_PLAIN).build());
System.out.println(message);
}
}
为了进行测试,我有一个简单的Country服务,其中提供了国家/地区列表。我确保测试InternalServerErrorException的抛出时将发生错误:
@GET
@Override
@Path("countries")
@Produces({"application/xml"})
public List<Country> findAll() {
try {
int i = Integer.parseInt("moo"); //<-- generate error
List<Country> countries = super.findAll();
return countries;
} catch (Exception ex) {
throw new InternalServerErrorException("I want this message to show at client side");
}
}
在我的客户端上,我有一个CountryClient使用以下方法:
public List<Country> findAll() throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path("countries");
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(new GenericType<List<Country>>(){});
}
在我的 Controller 中,我像这样使用它:
try {
CountryClientSSL cc = new CountryClientSSL();
cc.setUsernamePassword(USERNAME, PASSWORD);
ObservableList<Country> olCountries = FXCollections.observableArrayList(cc.findAll());
tblCountries.setItems(olCountries);
tcCountry.setSortType(SortType.ASCENDING);
tblCountries.getSortOrder().add(tcCountry);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
因此,每次我在客户端中使用findAll()方法时,我都会在输出窗口中看到以下信息:服务器端的
Info: I want this message to show at client side
和客户端端的HTTP 500 Internal Server Error
。是否可以在不使用
Response
作为返回类型的情况下在客户端(在catch块中)获取errorMessage? 我要实现的目标如下:当客户端发生错误时,用户可以将调试报告发送到我的JIRA实例,其中包含大量信息,例如客户端的stacktrace,有关系统的其他信息,已登录,...最好也将服务器的堆栈跟踪附加到那里。还是有更好的方法实现这一目标?
最佳答案
您可以使用response.readEntity(new GenericType<List<Country>>(){})
。这样,您仍然可以访问Response
。尽管在这种情况下将没有堆栈跟踪。当您尝试使用get(ParsedType)
时,客户端上只有一个异常(exception)。原因是使用get(ParsedType)
,没有其他方法可以处理错误状态。但是,使用Response
,开发人员应该对状态进行检查。所以该方法看起来更像
public List<Country> findAll() throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path("countries");
Response response = resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get();
if (response.getStatus() != 200) {
System.out.println(response.getHeaderString("errorResponse"));
return null;
} else {
return response.readEntity(new GenericType<List<Country>>(){});
}
}
尽管不是在 header 中,我只是将消息作为响应正文发送出去。这就是我
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity( message).type(MediaType.TEXT_PLAIN).build());
客户端
if (response.getStatus() != 200) {
System.out.println(response.readEntity(String.class));
return null;
}