如何从WebApplicationException中获得自定义消息?



我有一个向另一个控制器(B)发出post请求的服务a。这是我的服务发出post请求。控制器B与服务A不在同一个项目中,因此B抛出Bad request(400),服务A将400 request转到WebApplicationException:

WebClient client = tokenAuth.addAuthentication(WebClient.create(url))
.type(AccelaradMediaType.SMR_IMAGE_SHARE_V3_JSON)
.accept(AccelaradMediaType.SMR_SHARE_RESULT_JSON);
String response = client.post(body, String.class);
catch (WebApplicationException e) {
//get message from exception and print
}

这是我的服务发出post请求的另一个控制器(B)

@POST
@Path("/shares")
@Consumes({AccelaradMediaType.SMR_IMAGE_SHARE_V3_JSON, AccelaradMediaType.SMR_IMAGE_SHARE_V3_XML})
@Produces({AccelaradMediaType.SMR_SHARE_RESULT_JSON, AccelaradMediaType.SMR_SHARE_RESULT_XML})
public ShareResult shareV3() {
ShareResult result = null;
try {
result = shareStudies();
}
catch (StudyShareException e) {
LOG.error(e.getMessage(), e);
throw new BadRequestException(e.getMessage());
}
return result;
}
public ShareResult shareStudies() {
try {
//some logic
}
catch (InvitationException e) {
String message = "Invitation is pending";
throw new StudyShareException(message, e);
}
}

这里有StudyShareException类和BadRequestException类:

public class StudyShareException extends Exception {
public StudyShareException(String message, Throwable cause) {
super(message, cause);
}
}
public class BadRequestException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public BadRequestException(String message) {
this(message, null);
}
public BadRequestException(String message, Throwable cause) {
super(cause, Response.status(Response.Status.BAD_REQUEST).entity(message).type(MediaType.TEXT_PLAIN).build());
}
}

当服务A发出post请求时,它确实进入catch块,控制器B在堆栈跟踪中打印出错误" invite is pending"消息。

我的目标是打印出"邀请待定";从服务A中取出。我尝试了e.getResponse()或e.getResponse(). getentity()或e.getMessage(),没有任何工作。甚至有可能从服务A获得自定义消息吗?如果是这样,我该如何做到这一点?

为什么当服务B抛出StudyShareException时,您在服务A中捕获WebApplicationException?您需要在服务A中捕获正确的异常

try {
WebClient client = tokenAuth.addAuthentication(WebClient.create(url))
.type(AccelaradMediaType.SMR_IMAGE_SHARE_V3_JSON)
.accept(AccelaradMediaType.SMR_SHARE_RESULT_JSON);
String response = client.post(body, String.class);
catch (StudyShareException e) {
//get message from exception and print
}

现在,如果您试图捕获扩展WebApplicationException的所有异常,那么您应该使StudyShareException扩展WebApplicationException

话虽这么说,也许你根本不应该捕获任何异常,只是让服务A把服务b中抛出的异常泡起来。然而,这取决于你,你可能想在服务A中抛出不同的消息或不同的异常。

最新更新