从GCP发布/订阅中捕获错误代码

问题描述:

I am using go package for pub/sub. On my API dashboard I see this error(google.pubsub.v1.Subscriber.StreamingPull - error code 503). Per docs(https://cloud.google.com/pubsub/docs/reference/error-codes) it seems it is transient condition but better to implement backoff strategy(https://cloud.google.com/storage/docs/exponential-backoff). the question is I am not able to wrap my head where this error code is coming on Receive method.

Here is func:

err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
        // Dump message
        // log.Printf("Got message: %s", m.Data)

        // Decoding coming message
        err = json.NewDecoder(bytes.NewReader(m.Data)).Decode(&msg)
        if err != nil {
            log.Printf("Error decoding - %v", err)
        }

        // See streaming messages
        log.Printf(" %s : %s : Product updated for Product Id(%d) : Product Title(%s)",
            msg.AuthID,
            msg.TraceID,
            msg.Product.ID,
            msg.Product.Title,
        )

        //
        // Some business logic
        //


        // Acknowledge on recieve method
        m.Ack()
    })

    if err != context.Canceled {
        // if err != nil {
        return errors.Wrap(err, "Error occurred on recieve data from topic: blah")
    }

The Cloud Pub/Sub Go client library will retry this transient error on its own, you shouldn't need to handle it. Internally, the client library uses StreamingPull, where it sends a request and receives messages from the service as they are available. Occasionally, there can be a disconnection event requiring the connection to be reestablished. This is why you see the 503 error in the API dashboard. It should not be the case that your code sees an error in this scenario since the underlying library is handling it (including the use of exponential backoff, where relevant).