gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:45:11 26 4
gpt4 key购买 nike

我有一个服务 thrift 接口(interface)用于 result 方法如下:

exception SomeException {
1: string message;
}

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

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

最佳答案

这里是 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
}

关于exception - 如何实现基于Apache Thrift的golang服务有异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com