I've used an ExceptionMapper
on the server side, putting the custom exception in the Response's body. How can I retrieve the original exception on the client side, and throw it to the caller?
You can serialize the exception and include it as a part of the response:
public final class SerializingExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception exception) {
try {
final byte[] serializedException = serializeException(exception);
final String base64EncodedException = Base64.getEncoder().encodeToString(serializedException);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new Message(base64EncodedException))
.build();
} catch (Exception ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
private byte[] serializeException(Exception ex) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(ex);
oos.close();
return bos.toByteArray();
}
}
final class Message {
public Message(String exception) {
this.exception = exception;
}
public String exception;
}
Then on the client side you should do just the opposite:
byte[]
ByteArrayInputStream
ObjectInputStream
readObject()
the exception PS: This can be achieved without any buffering (ie without the byte[]
s) -> just use a StreamingOutput
as .entity()
and write to the provided output stream instead of a ByteArrayOutputStream
. The same applies for deserialization on the client side.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.