How to use java built-in exception in Thrift IDL

2020-08-01 06:38发布

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.

2条回答
时光不老,我们不散
2楼-- · 2020-08-01 06:56

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,
}
查看更多
女痞
3楼-- · 2020-08-01 07:22

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.

查看更多
登录 后发表回答