How Wrapcheck works: Identifying unwrapped external errors
masterWrapcheck is a linter designed to ensure that errors originating from external packages are wrapped before being returned. This helps identify the source of an error during debugging by providing context in logs.
The Problem: If you return an error from an external library directly, your logs might only show the library's error message (e.g., sql: error no rows), making it difficult to know which specific method or database call triggered it.
The Solution: Wrap the error at the call site using functions like fmt.Errorf. This adds context to the error chain.
Example of an unwrapped error (Linter Trigger):
if err := db.conn.Get(&u, sql, userID); err != nil {
return User{}, err // wrapcheck error: error returned from external package is unwrapped
}Example of a wrapped error (Correct):
if err := db.conn.Get(&u, sql, userID); err != nil {
return User{}, fmt.Errorf("failed to get user by ID: %v", err) // No error!
}// Correct way to handle external errors
if _, err := tx.Exec(sql, name, email, city); err != nil {
return fmt.Errorf("failed to insert user: %v", err)
}