简体   繁体   中英

How to retrieve a mapped exception from jersey?

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:

  • Unmarshal the (maybe JSON) response
  • Decode the base64 encoded exception to a byte[]
  • De-serialize the exception
    • Create a ByteArrayInputStream
    • Create ObjectInputStream
    • Just readObject() the exception
    • Do whatever you want with it on the client side

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM