-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.go
More file actions
50 lines (44 loc) · 1.63 KB
/
error.go
File metadata and controls
50 lines (44 loc) · 1.63 KB
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
// Package gn provides user-friendly messaging and error handling utilities
// for Go applications with colorized output and formatted messages.
package gn
import (
"errors"
"fmt"
)
// PrintErrorMessage attempts to print an error message if the error implements
// the Error interface. It uses errors.As to check if the error can be converted
// to the custom Error type, and if so, prints it with the appropriate formatting.
func PrintErrorMessage(err error) {
var target *Error
if errors.As(err, &target) {
target.print()
}
Message("\n<err>Error:</err> " + err.Error())
}
// ErrorCode represents a numeric code for categorizing errors.
type ErrorCode int
// Error is a custom error type that extends the standard error interface
// with additional fields for error codes, custom messages, and formatting variables.
// It can be used to create rich, user-friendly error messages.
type Error struct {
Code ErrorCode // Numeric code identifying the type of error
Err error // The underlying error
Msg string // User-friendly message template (can include format specifiers)
Vars []any // Variables to be formatted into the message template
}
// Error implements the error interface, returning the underlying error's message
// if available, or the custom message otherwise.
func (e *Error) Error() string {
if e.Err != nil {
return e.Err.Error()
}
if len(e.Vars) > 0 {
return fmt.Sprintf(e.Msg, e.Vars...)
}
return e.Msg
}
// print formats and displays the error message with the error icon and styling.
// This is an internal method called by PrintErrorMessage.
func (e *Error) print() {
print(errorMsgType, e.Msg, e.Vars)
}