File: errors.go

package info (click to toggle)
golang-github-johanneskaufmann-html-to-markdown 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,084 kB
  • sloc: makefile: 3
file content (66 lines) | stat: -rw-r--r-- 1,266 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cmd

import (
	"fmt"
	"io"

	"github.com/muesli/termenv"
)

type CLIError struct {
	cause    error
	printers []Printer
}

func extractCLIError(err error) (CLIError, bool) {
	if cliErr, ok := err.(*CLIError); ok {
		return *cliErr, true
	}

	return CLIError{
		cause: err,
	}, false
}

func NewCLIError(cause error, printers ...Printer) error {
	return &CLIError{
		cause:    cause,
		printers: printers,
	}
}
func (e CLIError) Error() string {
	return e.cause.Error()
}
func (e CLIError) PrintDetails(w io.Writer) {
	errPrinter := ColoredBox("error", e.cause.Error())

	// Prepend the error printer
	e.printers = append([]Printer{errPrinter}, e.printers...)

	for _, printer := range e.printers {
		w.Write([]byte("\n"))
		printer.Print(w)
	}
	w.Write([]byte("\n"))
}

func (cli CLI) PrintErr(err error) {
	if err == nil {
		return
	}

	e, _ := extractCLIError(err)
	e.PrintDetails(cli.Stderr)
}
func (cli CLI) PrintWarn(err error) {
	if err == nil {
		return
	}

	output := termenv.NewOutput(cli.Stderr)

	prefix := output.String("warning:").Background(termenv.ANSIYellow).Foreground(termenv.ANSIBrightWhite).String()
	message := output.String(err.Error()).Foreground(termenv.ANSIYellow).String()

	fmt.Fprintf(cli.Stderr, "\n%s %s\n\n", prefix, message)
}