Repository navigation
Custom error message formatter #2513
|
I would like to use a custom error message formatter that will handle urfave/cli errors (e.g. Something like Can anyone give me some pointers about how to do this? |
Replies: 2 comments
|
You can use package main
import (
"context"
"errors"
"fmt"
"os"
"github.com/urfave/cli/v3"
)
func main() {
cmd := &cli.Command{
Name: "demo",
ExitErrHandler: func(_ context.Context, cmd *cli.Command, err error) {
if err == nil {
return
}
code := 1
var ec cli.ExitCoder
if errors.As(err, &ec) {
code = ec.ExitCode()
}
fmt.Fprintf(cmd.ErrWriter, "\x1b[31merror:\x1b[0m %v\n", err)
os.Exit(code)
},
}
if err := cmd.Run(context.Background(), os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
One thing to watch: the error is still returned to the caller if your handler returns. This example exits in the handler so it won't also get printed by the code after If you're using v2, the hook is on |
|
Thanks, this works perfectly! Calling |
You can use
ExitErrHandlerfor this. It replaces the default error handler, so you can add your own formatting. Here's a small v3 (github.com/urfave/cli/v3) example: