eclipse-paho / paho.mqtt.golang

Other
2.77k stars 534 forks source link

can you add connect fail Handler,reconnect fail Handler ? thanks #579

Open wthsjy opened 2 years ago

wthsjy commented 2 years ago

like this:

    if c.options.ConnectRetry {
                         if c.options.ConnectFail != nil {
                go c.options.ConnectFail( err)
            }

                DEBUG.Println(CLI, "Connect Failed, Sleeping for", int(c.options.ConnectRetryInterval.Seconds()), "seconds and will then retry, error:", err.Error())
                time.Sleep(c.options.ConnectRetryInterval)

                if atomic.LoadUint32(&c.status) == connecting {
                    goto RETRYCONN
                }
            }
MattBrittan commented 2 years ago

This is not something that I personally am particularly interested in implementing; however I'll consider a pull request.

Note that I am concerned about the continuing increase in the number of options so feel that this would best be implemented in a more generic way. I'm thinking something like:

type CommsNotification int64
const (
        Undefined CommsNotification = iota
    AttemptConnectionFailed
        ConnectRetryFailed
)

// CommsNotificationHandler is invoked upon various changes to status of the connection to the broker
type CommsNotificationHandler func(type CommsNotification, err error.Error, extraData interface{})

// SetConnectionLostHandler will set the OnConnectionLost callback to be executed
// in the case where the client unexpectedly loses connection with the MQTT broker.
func (o *ClientOptions) SetCommsNotificationHandler(handler CommsNotificationHandler) *ClientOptions {
    o.CommsNotificationHandler = CommsNotificationHandler
    return o
}

This is a rough sketch; my thinking is that this could be expanded to include a range of notifications (e.g. TCP Dial failed, Clean disconnect etc) as required and users could ignore messages they are not interested in. The extraData field is there because in some cases more info would be nice (i.e. knowing which broker attemptConnection() failed to connect to).

Open to any suggestions on this.

wthsjy commented 2 years ago

@MattBrittan you're right.

Looking forward to this function!

i need to get the error connect information in our project, and then report it to the server for analysis