如何在 Thrift IDL 中使用 Java 内置异常 [英] How to use java built-in exception in Thrift IDL

查看:23
本文介绍了如何在 Thrift IDL 中使用 Java 内置异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Thrift IDL 中抛出一些 Java 内置异常,例如 IOException.

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

像这样:

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

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

但是,Thrift 编译器警告未定义 ioexception.

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

推荐答案

每个 java 异常都是可序列化的,因此可以将其包装到 thrift 异常中.

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

节俭代码:

exception SerializedException
{
    1: required binary payload
}

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

Java 服务器代码:

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 客户端代码:

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 中使用 Java 内置异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆