How to use java built-in exception in Thrift IDL

2020-08-01 06:37发布

问题:

I'd like to throws some java built-in exception such IOException in the Thrift IDL.

like this:

service B{
     void removeLease() throws (1:ioexception e),
}

however, the Thrift compiler warns that ioexception doesn't be defined.

回答1:

Every java exception is serializable, so it's possible to wrap it into thrift exception.

Thrift code:

exception SerializedException
{
    1: required binary payload
}

service MyService
{
    int method(1: required string param) throws (1: SerializedException serializedException);
}    

Java server code:

class MyServiceImpl implements MyService.Iface {
    int method(String param) throws SerializedException {
        try {
            ...
        } catch (IOException ex) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            new ObjectOutputStream(os).writeObject(ex);
            throw new SerializedException(os.toByteArray());
        }
    }
}

Java client code:

try {
    int r = myService.method("param");
} catch (SerializedException ex) {
    Exception nested = <Deserialize ex.payload via ByteArrayInputStream>
    ...
}

So, the client gets full exception together with stacktrace, etc. We use this approach is several projects, it works for sure.



回答2:

Thrift IDL is language agnostic.You cannot use built-in exceptions(like IOException in this case) You can define and use your own "ioexception"

exception ioexception
{
 1:string msg,
}