Changing How Errors Are Handled

All built-in errors have a default handler they use when they are returned. However, you might want to change how errors look or behave in certain situations.

Logging

If you want to change how InternalErrors are logged, or if you want to use an error tracker like sentry, you can change the errors.Log function:

import (
    "github.com/getsentry/sentry-go"
    "github.com/mavolin/adam/pkg/errors"
    log "github.com/sirupsen/logrus"
)

func changeLogging() {
    errors.Log = func(err error, ctx *plugin.Context) {
        log.WithFields(log.Fields{
                "err": err,
                "cmd_id": ctx.InvokedCommand.ID,
            }).
            Error("internal error in command")
        
        sentry.CaptureException(err)
    }
}

Embeds

All error handlers that send error messages to the user use the error and info embeds provided by package errors. So to change the looks of errors it's often easier to simply alter the embeds using errors.SetErrorEmbed and errors.SetInfoEmbed instead of changing every error handler.

Type-Specific Handling

If you want to change how certain error types are handled, you can replace the handler function of the error. Every error (except InformationalError) has a handler function titled Handle{{error_name}}. You can use the default handler as a reference.

Individual handling

If you want to change how individual errors are handled, the correct place is the bot's error handler. You can change it by setting a custom one in the bots bot.Options.

If you simply want to ignore errors, you can just filter those out and then call bot.DefaultErrorHandler.

cmd/mybot/main.go
bot, err := bot.New(bot.Options{
    Token: os.Getenv("DISCORD_BOT_TOKEN"),
    ErrorHandler: func(err error, s *state.State, ctx *plugin.Context) {
        if errors.Is(err, bot.ErrUnknownCommand) {
            return
        }
        
        bot.DefaultErrorHandler(err, s, ctx)
    },
})

Last updated

Was this helpful?