Morgana is a robust and flexible error management library for Go, designed to enhance error handling and debugging by providing rich metadata, stack traces, and structured error objects.
- Rich metadata support for errors.
- Stack trace generation (single frame and full call stack).
- Custom error codes and types.
- JSON and Safe JSON serialization (with redaction).
- Easy wrapping, chaining, cause tracking, and joining of errors.
- HTTP response writer helper.
- Logger fields extraction for structured logs.
- Panic capture helpers.
- Context trace enrichment.
- gRPC status code mapping helpers.
go get -u github.com/bi0dread/morganaerr := morgana.New("ValidationError").
WithStatusCode(400).
WithCustomCode("INVALID_INPUT").
WithMessage("Invalid input provided for field: %s", "email")
fmt.Println(err.String())err := morgana.New("NetworkError").
WithAddMetaDataKey("endpoint", "/api/v1/resource").
WithAddMetaDataKey("method", "GET")
fmt.Println(err.GetMetaData())originalErr := fmt.Errorf("connection timeout")
wrappedErr := morgana.Wrap(originalErr, morgana.New("NetworkError").ToError())
fmt.Println(morgana.GetStringDetail(wrappedErr))cause := fmt.Errorf("disk full")
err := morgana.New("IOError").WithMessage("failed writing file").WithCause(cause)
fmt.Println(err.Cause()) // root cause: disk full
other := fmt.Errorf("low-level error")
err = err.WithError(other) // pushes a stack Morgana from other
fmt.Println(err.GetMorganaStackErrors())err := morgana.New("FileError").
WithMessage("File not found: %s", "config.yaml").
WithFullStack(2, 64)
fmt.Println(err.GetStackFrames())err := morgana.New("SecretError").
WithAddMetaDataKey("token", "super-secret").
WithRedactedKey("token")
fmt.Println(err.ToJsonSafe()) // token value redactedfunc handler(w http.ResponseWriter, r *http.Request) {
m := morgana.New("Unauthorized").WithStatusCode(http.StatusUnauthorized).WithMessage("auth required")
m.WriteHTTP(w, true) // write safe JSON
}err := morgana.Recover(func(){
panic("boom")
})
if err != nil {
fmt.Println(morgana.GetStringDetail(err))
}err := morgana.Join(
fmt.Errorf("first"),
morgana.New("Second").WithMessage("second").ToError(),
)
fmt.Println(morgana.GetStringDetail(err))m := morgana.New("NotFound").WithStatusCode(http.StatusNotFound).WithMessage("missing")
code := m.ToGRPCCode() // 5 (NotFound)
_ = code
m.FromGRPCCode(3) // InvalidArgument -> 400
fmt.Println(m.GetStatusCode())WithTrace(ctx)pulls common correlation IDs from context.WithID/ GetIDprovides an error correlation ID.WithFieldError/ GetFieldErrorshelps shape validation errors (HTTP 422 style).ToFields()returns structured fields for logging.EmpoimplementsUnwrap()and can carry acausefor standard error traversal.