如何实现基于Apache Thrift的golang服务,但有异常?

时间:2015-12-04 15:15:38

标签: exception go exception-handling thrift

我为result方法提供了服务 thrift 界面,如下所示:

exception SomeException {
    1: string message;
}

string result(
    1: string token,
    2: string identifier
) throws (
    1: SomeException ex,
);

我如何在 golang 中正确实现此功能?我希望为这个Thrift服务的客户端正常抛出异常。

2 个答案:

答案 0 :(得分:3)

Apache Thrift tutorial for Go在这里发挥作用。本教程由small service

组成
enum Operation {
    ADD = 1,
    SUBTRACT = 2,
    MULTIPLY = 3,
    DIVIDE = 4
}

struct Work {
    1: i32 num1 = 0,
    2: i32 num2,
    3: Operation op,
    4: optional string comment,
}

service Calculator extends shared.SharedService {
    i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),

    // some other methods ...
}

如果客户端以这种方式将计算操作传递给服务器:

work := tutorial.NewWork()
work.Op = tutorial.Operation_DIVIDE
work.Num1 = 1
work.Num2 = 0
quotient, err := client.Calculate(1, work)
if err != nil {
    switch v := err.(type) {
    case *tutorial.InvalidOperation:
        fmt.Println("Invalid operation:", v)
    default:
        fmt.Println("Error during operation:", err)
    }
    return err
} else {
    fmt.Println("Whoa we can divide by 0 with new value:", quotient)
}

服务器应抛出异常,如下所示。当传递w.Op的某个未知值时会发生类似的事情:

func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32, err error) {

switch w.Op {
    case tutorial.Operation_DIVIDE:
        if w.Num2 == 0 {
            ouch := tutorial.NewInvalidOperation()
            ouch.WhatOp = int32(w.Op)
            ouch.Why = "Cannot divide by 0"
            err = ouch
            return
        }
        val = w.Num1 / w.Num2
        break

    // other cases omitted

    default:
        ouch := tutorial.NewInvalidOperation()
        ouch.WhatOp = int32(w.Op)
        ouch.Why = "Unknown operation"
        err = ouch
        return
    }

    // more stuff omitted
}

答案 1 :(得分:0)

简短的回答是Thrift Interfaces实现了error interfaceError() string函数)。因此可以像任何error一样返回,通常像return nil, err