Last active
February 23, 2024 11:58
-
-
Save rednafi/d090a16ba6ddd19c7fe8bdaae746205c to your computer and use it in GitHub Desktop.
Anemic stack traces in Go. Read the blog on https://rednafi.com/go/anemic_stack_traces/
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 ( | |
"fmt" | |
"io" | |
"os" | |
"runtime" | |
"strings" | |
) | |
var Debug bool | |
type Error struct { | |
Op string | |
Path string | |
LineNo int | |
FileName string | |
Err error | |
Debug bool | |
} | |
func (e *Error) Error() string { | |
if e.Debug { | |
return fmt.Sprintf( | |
"%s: %s: %s\n\t%s:%d", e.Op, e.Path, e.Err, e.FileName, e.LineNo, | |
) | |
} | |
msg := e.Err.Error() | |
msgs := strings.Split(msg, ":") | |
msg = strings.TrimSpace(msgs[len(msgs)-1]) | |
return fmt.Sprintf("%s: %s: \n\t%s", e.Op, e.Path, msg) | |
} | |
func NewError(op string, path string, err error) *Error { | |
_, file, line, ok := runtime.Caller(1) | |
if !ok { | |
file = "???" | |
line = 0 | |
} | |
return &Error{ | |
Op: op, | |
Path: path, | |
LineNo: line, | |
FileName: file, | |
Err: err, | |
Debug: Debug, | |
} | |
} | |
func copyFile(src, dst string, debug bool) error { | |
// Open the source file for reading. | |
sourceFile, err := os.Open(src) | |
if err != nil { | |
return NewError("os.Open", src, err) | |
} | |
defer sourceFile.Close() | |
// Create the destination file for writing. | |
destFile, err := os.Create(dst) | |
if err != nil { | |
return NewError("os.Create", dst, err) | |
} | |
defer destFile.Close() | |
// Copy the contents from source to destination file. | |
_, err = io.Copy(destFile, sourceFile) | |
if err != nil { | |
return NewError("io.Copy", dst, err) | |
} | |
// Ensure that the destination file's content is successfully written. | |
err = destFile.Sync() | |
if err != nil { | |
return NewError("destFile.Sync", dst, err) | |
} | |
return nil | |
} | |
func main() { | |
// Define the source and destination file paths. | |
src := "/path/to/source/file" | |
dst := "/path/to/destination/file" | |
Debug = false | |
// Call fileCopy and handle any errors. | |
err := copyFile(src, dst, true) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "%v\n", err) | |
os.Exit(1) | |
} | |
fmt.Println("File copied successfully.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment