How to wrap errors with additional context information in Go?

In Go, you can wrap errors with additional context information using the errors.Wrap function provided by the github.com/pkg/errors package, known as the "errors package". Here's how you can do it:

  1. Import the github.com/pkg/errors package:
import ( "github.com/pkg/errors" )
  1. Wrap an error with additional context information using errors.Wrap:
err := errors.New("Something went wrong") wrappedErr := errors.Wrap(err, "Additional context information")

The errors.Wrap function takes two arguments: the original error and a string containing the additional context information. It returns a new error that wraps the original error with the provided context information.

  1. Retrieve the context information later if needed:
if wrappedErr != nil { fmt.Printf("Error: %s\n", wrappedErr.Error()) // Print the error message including context // Or you can retrieve the unwrapped original error using errors.Cause originalErr := errors.Cause(wrappedErr) fmt.Printf("Original Error: %s\n", originalErr.Error()) }

You can use wrappedErr.Error() to get the complete error message, including the context information. Additionally, if you need to access the unwrapped original error, you can use errors.Cause function provided by the "errors package".

By wrapping errors with context information, you can provide more useful information about the error without losing the underlying error details. This helps in understanding the error and diagnosing issues more easily.