How to use java built-in exception in Thrift IDL

心已入冬 提交于 2019-12-12 09:25: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,
}


来源:https://stackoverflow.com/questions/11755292/how-to-use-java-built-in-exception-in-thrift-idl

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