Last active
August 8, 2024 21:24
-
-
Save ObsidianCat/3033a95ce3e5b0c404134d05d5c80eca to your computer and use it in GitHub Desktop.
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 main | |
import ( | |
"errors" | |
"fmt" | |
customError "github.com/pkg/errors" | |
) | |
type stackTracer interface { | |
StackTrace() customError.StackTrace | |
} | |
func main() { | |
fmt.Println("Example using standard library:") | |
errStd := readFileStandard() | |
if errStd != nil { | |
fmt.Printf("%v\n", errStd) // This will only print the error message | |
fmt.Printf("%+v\n", errStd) // This will print the error message, as there is no stack trace | |
} | |
fmt.Println("\nExample using pkg/errors:") | |
err := readFilePkg() | |
if err != nil { | |
fmt.Printf("%v\n", err) // This will only print the error message | |
fmt.Printf("%+v\n", err) // This will print the error message and the stack trace | |
} | |
fmt.Println("Example using DataDog way to print stack trace:") | |
var stack string | |
if serr, ok := err.(stackTracer); ok { | |
st := serr.StackTrace() | |
stack = fmt.Sprintf("%+v", st) | |
if len(stack) > 0 && stack[0] == '\n' { | |
stack = stack[1:] | |
} | |
fmt.Printf("\nStack trace:\n%s\n", stack) | |
} | |
} | |
// Standard library error handling | |
func readFileStandard() error { | |
return fmt.Errorf("failed to read file: %w", readStandard()) | |
} | |
func readStandard() error { | |
return errors.New("an error occurred") | |
} | |
// pkg/errors error handling | |
func readFilePkg() error { | |
return customError.Wrap(readPkg(), "failed to read file") | |
} | |
func readPkg() error { | |
return customError.New("an error occurred") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment