Created
February 23, 2025 23:31
-
-
Save rednafi/aa3e9af16058d0d3381e928347fb2731 to your computer and use it in GitHub Desktop.
Some go err handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package errs | |
import ( | |
"fmt" | |
"runtime" | |
) | |
// Error represents a custom error with function name, line number, and message. | |
type Error struct { | |
lineno int | |
funcName string | |
msg string | |
cause error | |
} | |
// Error implements the error interface. | |
func (e *Error) Error() string { | |
if e.cause != nil { | |
return fmt.Sprintf("%s:%d: %s: %v", e.funcName, e.lineno, e.msg, e.cause) | |
} | |
return fmt.Sprintf("%s:%d: %s", e.funcName, e.lineno, e.msg) | |
} | |
// Unwrap returns the underlying cause of the error. | |
func (e *Error) Unwrap() error { | |
return e.cause | |
} | |
// New creates a new error with function name and line number. | |
func New(msg string) error { | |
funcName, lineno := callerInfo() | |
return &Error{ | |
funcName: funcName, | |
lineno: lineno, | |
msg: msg, | |
} | |
} | |
// Wrap wraps an existing error with additional context. | |
func Wrap(err error, msg string) error { | |
if err == nil { | |
return nil | |
} | |
funcName, lineno := callerInfo() | |
return &Error{ | |
funcName: funcName, | |
lineno: lineno, | |
msg: msg, | |
cause: err, | |
} | |
} | |
// Wrapf wraps an existing error with formatted message. | |
func Wrapf(err error, format string, args ...interface{}) error { | |
if err == nil { | |
return nil | |
} | |
funcName, lineno := callerInfo() | |
return &Error{ | |
funcName: funcName, | |
lineno: lineno, | |
msg: fmt.Sprintf(format, args...), | |
cause: err, | |
} | |
} | |
// callerInfo retrieves the calling function name and line number. | |
func callerInfo() (string, int) { | |
pc, _, line, ok := runtime.Caller(2) | |
if !ok { | |
return "unknown", 0 | |
} | |
fn := runtime.FuncForPC(pc) | |
if fn == nil { | |
return "unknown", line | |
} | |
return fn.Name(), line | |
} | |
func main() { | |
err1 := New("initial error") | |
fmt.Println(err1) | |
err2 := Wrap(err1, "wrapped error") | |
fmt.Println(err2) | |
err3 := Wrapf(err2, "formatted %s", "error") | |
fmt.Println(err3) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment