How to use java built-in exception in Thrift IDL

孤人 提交于 2019-12-04 22:28:10

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.

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,
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!