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

Max*_*hka 5 exception-handling exception thrift go

我有一个用于方法的服务节俭接口,result如下所示:

exception SomeException {
    1: string message;
}

string result(
    1: string token,
    2: string identifier
) throws (
    1: SomeException ex,
);
Run Code Online (Sandbox Code Playgroud)

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

Jen*_*nsG 5

这里Go 的 Apache Thrift 教程就派上用场了。本教程包含一个小服务

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 ...
}
Run Code Online (Sandbox Code Playgroud)

如果客户端通过这种方式向服务器传递一个计算操作:

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)
}
Run Code Online (Sandbox Code Playgroud)

服务器应该抛出异常,如下所示。当传递一些未知值时,会发生类似的情况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
}
Run Code Online (Sandbox Code Playgroud)