Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement golang service based on Apache Thrift with exceptions?

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.

like image 965
Maxim Galushka Avatar asked Sep 26 '22 00:09

Maxim Galushka


1 Answers

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
}
like image 90
JensG Avatar answered Oct 03 '22 14:10

JensG