I have a service thrift interface for result
method as follows:
exception SomeException {
1: string message;
}
string result(
1: string token,
2: string identifier
) throws (
1: SomeException ex,
);
How di I implement this properly in golang? I want exceptions to be thrown properly for clients of this Thrift service.
Here the Apache Thrift tutorial for Go comes into play. The tutorial consists of a 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 ...
}
If the client passes a calculation operation to the server in this way:
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)
}
the server should throw an exception as shown below. A similar thing happens when some unknown value for the w.Op
is passed:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With