Skip to content

Latest commit

 

History

History
995 lines (802 loc) · 38 KB

error-handling.md

File metadata and controls

995 lines (802 loc) · 38 KB
title Error Handling
weight 6
description Complete guide to error handling in Loom - defining errors, transport mapping, custom types, and best practices.
llm_optimized true
aliases

Loom provides a robust error handling system that enables you to define, manage, and communicate errors effectively across your services. This guide covers everything from basic error definitions to advanced customization.

Overview

Loom takes a "batteries included" approach to error handling where errors can be defined with minimal information (just a name) while also supporting completely custom error types when needed.

Key features:

  • Service-level and method-level error definitions
  • Default and custom error types
  • Transport-specific mapping for HTTP, JSON-RPC, and gRPC
  • Generated helper functions for error creation
  • RFC 9457 application/problem+json responses for default HTTP errors
  • Automatic contract generation

Defining Errors

Each API, service or method scope may declare an exact error name only once. Repeating Error("boom") in the same scope is a design error, even when the types match. Remove the repeated declaration before regenerating. A method may declare Error("boom", CustomError) to override its service's boom error; separate services and methods may also reuse names. Names are case-sensitive, and distinct wire names remain valid even when their generated Go names collide. API error definitions remain reusable definitions rather than automatically inherited method errors. Valid designs retain their generated output.

Nullable error payloads

HTTP and JSON-RPC errors can carry explicit JSON null. A nullable payload is data, so return its generated named error owner, not loom.Nullable[T] itself:

// Design: Error("missing", Details, func() { Nullable() })
failure, err := service.NewMissingError(loom.NullValue[service.Details]())
if err != nil {
    return err
}
return failure

The generated constructor returns (*MissingError, error). Its Payload() method returns (loom.Nullable[Details], error), preserving absent, explicit null and concrete values. The owner retains the declared error name even for null. If the payload has an ErrorName field, a concrete value must match that declared name. Construction and transport projection both check it; neither rewrites the field. A nil owner is invalid. Generated names follow the usual collision allocation. Regenerate transports and use the generated constructor when adopting this behavior.

A response with a body cannot encode an absent nullable payload. JSON-RPC keeps explicit data: null distinct from missing data. If several declared errors with the same JSON-RPC code could accept null, decoding rejects the ambiguity; use distinct codes or a concrete value with an unambiguous selector. gRPC still rejects nullable error payloads.

For results and errors, HTTP Body("field") selects a member of a concrete parent. Null or absent parents cannot supply that member and fail before response publication. A nullable selected member may itself be null; decoding that member reconstructs a concrete parent. A whole-body null with excluded header or cookie fields remains null only when no mapped metadata is supplied. Incoming null plus metadata is rejected, and absent metadata defaults do not create a parent. A required mapped header or cookie still prevents a null response.

A selected member must be supplied even when it is optional in the parent type. An absent selected member fails before publication; a supplied zero, empty value or explicitly nullable null retains its own contract. A response containing only mapped headers/cookies also requires a concrete parent. Its client reconstructs that parent even when all optional metadata is absent, applying existing defaults and requiredness checks. A truly bodyless response without metadata keeps its existing absence behavior. Regenerate clients and servers for these corrections.

JSON-RPC also preserves supplied empty error data ("", {}, or []) instead of omitting it; only absent data is omitted.

Nullable default errors

Applying Nullable() to the callback of Error("missing", ...) uses a generated nominal error owner with a loom.Nullable[loom.ServiceError] payload. MakeMissing(cause) returns a concrete owner with the usual instance ID, cause, trait seeds and remedy. NewMissingError(loom.NullValue[loom.ServiceError]()) constructs explicit null. No additional response mapping is required for declaring the error.

A concrete owner stores one native occurrence. errors.As can expose that *loom.ServiceError; mutations are observed by later Payload() and transport projection. A mismatched Name is rejected, including after mutation. Payload values returned by Payload() are struct copies: assigning their scalar fields does not mutate the stored occurrence. Referenced objects retain ordinary Go aliasing. Null and absent payloads expose no native occurrence. Errors are not synchronized for concurrent application mutation.

Mapped whole nullable problem bodies use application/json for concrete and null values. Explicit application/problem+json is rejected for a nullable whole body because that media type requires a problem object. Nonnullable default errors keep their existing problem media type. A nonnullable authored object Body projection requires a concrete parent, just like member selection; null and absent parents fail before publication. Clients reconstruct a concrete parent from that nonnullable body.

When a designed problem projection omits code, clients recover the error name from its declared transport alternative. If the body or mapped metadata conveys code, even an empty value must agree with that declaration. Omitted traits remain false; they are never inferred from HTTP status or the factory's seeds.

An error with no Response mapping still uses the ordinary fallback encoder. Fallback does not promise the designed nullable body: a valid concrete default owner supplies its native ID and traits, while null, absent and invalid payloads supply no native occurrence. HTTP then uses its existing generic fault document; JSON-RPC retains its existing named-error/remedy fallback. An outer remedy or safe-message wrapper keeps its established precedence. Resolution stops at the first named owner and never selects a native error from an independent join.

Merging validation errors

Use the return value of loom.MergeErrors(first, second). When both operands are nonnil, it creates a new ServiceError and never changes either input or an earlier merge result. Nil is the identity: merging with nil returns the other operand unchanged, including its concrete type.

The merge retains the first contribution's ID, field and remediation metadata, selects the second name only when the first name is error, joins messages with ; , and ANDs the timeout, temporary and fault flags. This operation accumulates related validation errors; use errors.Join to represent independent failures without assigning one contribution's contract to the aggregate.

ServiceError.History() returns detached original contributions in order, including duplicates. Editing the returned slice, entries, fields or remedies does not alter the source or later history reads. WithErrorHistory explicitly sets the receiver's history, snapshots its inputs, and flattens supplied merged entries. Original causes remain reachable through errors.Is and errors.As; the framework does not clone arbitrary cause objects or make mutable errors safe for concurrent application writes.

For example, after ab := loom.MergeErrors(a, b) and abc := loom.MergeErrors(ab, c), a, b and ab retain their original data, while abc has history [a, b, c]. A call that discards the return value does not update either operand. This replaces the former mutation contract; there is no separate legacy merge API.

Independent joined failures over gRPC

An errors.Join(a, b) with multiple nonnil branches represents the complete failure. gRPC evaluates each branch's explicit or designed status, retains the code only when every branch agrees, and otherwise uses Unknown. Reordering branches cannot change that decision. A join containing only one nonnil error is a transparent wrapper.

The aggregate uses generic ErrorResponse details with the full joined error message, name fault, Fault=true, and Timeout=false and Temporary=false. It does not publish one branch's custom details, validation history or retry traits as if they described the whole failure. For example:

Failure Status Details
Two independent Unavailable errors Unavailable Full generic failure; no inferred retry trait
Canceled joined with Unavailable Unknown Both failures
Designed validation error joined with an unclassified cleanup error Unknown Both failures, not the validation error's custom detail

An explicit outer ServiceError, GRPCStatus, or recognized designed error owns the whole response and takes precedence over its causes. Ordinary single-error wrappers preserve that contract. The runtime checks ownership before traversing causes; it does not use a tree-wide errors.As match to choose an independent branch. A nonnil error with an OK status becomes Unknown. Applications that want an aggregate retry policy must express it in an outer error contract. This replaces first-branch selection without a compatibility mode and applies equally to generated unary and streaming servers.

API-Level Errors

Define reusable errors at the API level with transport mappings:

var _ = API("calc", func() {
    Error("invalid_argument")
    HTTP(func() {
        Response("invalid_argument", StatusBadRequest)
    })
})

var _ = Service("divider", func() {
    Error("invalid_argument")  // Reuses API-level definition
    
    Method("divide", func() {
        Error("div_by_zero", DivByZero, "Division by zero")
    })
})

Service-Level Errors

Service-level errors are available to all methods within a service:

var _ = Service("calc", func() {
    Error("invalid_arguments", ErrorResult, "Invalid arguments provided")
    
    Method("divide", func() {
        // Can return invalid_arguments without explicitly declaring it
    })

    Method("multiply", func() {
        // Can also return invalid_arguments
    })
})

Method-Level Errors

Method-specific errors are scoped to a particular method:

var _ = Service("calc", func() {
    Method("divide", func() {
        Payload(func() {
            Field(1, "dividend", Int)
            Field(2, "divisor", Int)
            Required("dividend", "divisor")
        })
        Result(func() {
            Field(1, "quotient", Int)
            Required("quotient")
        })
        Error("div_by_zero")  // Only available to this method
    })
})

An error declared with Error(...) but omitted from the method's JSON-RPC Response(...) mappings has no typed transport contract. Generated clients therefore return the raw *jsonrpc.RawErrorResponse. They do not decode or validate its data field. HTTP Response(...) mappings never create a JSON-RPC error contract. Add a JSON-RPC Response mapping when callers need a typed, validated service error.


Error Types

Default ErrorResult

The default ErrorResult uses loom.ServiceError in service implementations and generated clients. Its Go fields include:

  • Name: The error name as defined in the DSL
  • ID: Unique identifier for the error instance
  • Message: Descriptive error message
  • Temporary: Whether the error is transient
  • Timeout: Whether the error was caused by a timeout
  • Fault: Whether the error was a server-side fault
var _ = Service("divider", func() {
    Error("DivByZero", ErrorResult, "Division by zero")
    Error("ServiceUnavailable", ErrorResult, "Service temporarily unavailable", func() {
        Temporary()
    })
})

Generated helper functions:

// MakeDivByZero builds a loom.ServiceError from an error
func MakeDivByZero(err error) *loom.ServiceError {
    return loom.NewServiceError(err, "DivByZero", false, false, false)
}

// MakeServiceUnavailable builds a loom.ServiceError from an error
func MakeServiceUnavailable(err error) *loom.ServiceError {
    return loom.NewServiceError(err, "ServiceUnavailable", true, false, false)
}

Distinct error names retain distinct generated factories even when their preferred Go names match. For example, foo_bar and FooBar can produce MakeFooBar and MakeFooBar2. Factories share the service package namespace with generated types; a conflicting type also receives a suffix. Use the generated declarations instead of predicting suffixes. Regenerate and update handwritten references to renamed factories or types. Authored error names and transport status mappings stay the same. Custom user error types do not receive these built-in factories.

Selecting Built-in Problem Fields

A response for a built-in error may select a public problem field, for example Body("detail"), or map fields to headers and cookies. Loom first converts the service error into its public problem representation, including safe-message selection, instance URI, retry guidance and explicit type/title metadata. The body and mapped fields all use that representation. Generated clients reconstruct the error from the fields actually present in the body and their wire mappings.

A scalar selection uses the ordinary response media type, usually application/json; it is not a complete application/problem+json document. The existing body-selection rules still map other attributes to automatic headers. To author a body with only listed fields, use an explicit Body(func() { Attribute("detail") }) shape. A custom error formatter receives the whole error and replaces the body, including for a selected scalar. Its output must agree with the intended client contract. The selected native member is not required when a formatter replaces it. Native payload presence and mapped headers or cookies keep their own requirements; a formatter does not create a concrete parent for those mappings. Without a formatter, selecting an absent optional field, such as an unset retry_hint, fails before publication.

Regenerate HTTP clients and servers to adopt these projection corrections.

Custom Error Types

For more detailed error information, define custom error types:

var DivByZero = Type("DivByZero", func() {
    Description("DivByZero is the error returned when using value 0 as divisor.")
    Field(1, "message", String, "Error message")
    Field(2, "dividend", Int, "Dividend that was used")
    ErrorName(3, "name", String, "Error name")
    Required("message", "dividend", "name")
})

var _ = Service("divider", func() {
    Method("divide", func() {
        Error("DivByZero", DivByZero, "Division by zero")
    })
})

When one custom type represents multiple errors in the same method, use ErrorName to identify the routing field. The field is part of the response body by default. To keep routing metadata exclusively in the Loom-Error header, map it as a response header for every named response:

Response("forbidden", StatusForbidden, func() {
    Header("name:loom-error")
})

The generated server writes the header, the generated client restores the field from it, and the field is omitted from the response body and OpenAPI schema. This supports several named errors with one unchanged payload shape, including multiple errors that use the same HTTP status.

If a named error has its own HTTP status, you can instead declare that status as the source of its ErrorName field:

Response("forbidden", StatusForbidden, func() {
    ErrorNameFromStatus()
})

The generated client sets the field to "forbidden" after selecting status 403. The server omits the automatic Loom-Error header, and the implicit response body and OpenAPI body schema omit the field. The application still sets the field when returning the error so the server can select the named response. Regenerate both client and server after adding this mapping.

ErrorNameFromStatus requires a custom error with a required ErrorName field. Its declared error name must satisfy the field's constraints. The status must select exactly one response on each effective endpoint, including inherited responses and success responses. For example, separate 400 and 404 mappings are accepted; two named errors at 400 are rejected if either uses this option.

This source is exclusive: do not also put the field in an explicit Body, header or cookie mapping, or declare a Loom-Error header. Other required fields still need their own reconstruction sources. Explicit selected and empty bodies are supported when they meet that rule. An extra, unbound Loom-Error received by a status-derived client does not override the declared identity.

Existing header mappings remain strict: a missing required header is a decoding error even when the status is unique. This option is available only for HTTP error responses; JSON-RPC and gRPC retain their own error identity rules.

OpenAPI combines responses that share a status. Distinct media types retain their own schemas; alternatives within one media type use anyOf, since error shapes may overlap. Header schemas also use anyOf when they differ. A header is required only when every alternative requires it. Descriptions and examples are retained in deterministic order, with examples named by their response. The generated server, client, and response contract manifest continue to select the individual designed error.

Conflicting response component names, links, extension values, description omission settings, or non-schema media/header metadata stop OpenAPI generation with the endpoint and status in the diagnostic. Give these alternatives compatible metadata. Regenerate the OpenAPI files to include all alternatives.

Use Body("field") to send one field of a custom error as the entire response body. For example, a string field can carry an HTML error page:

Response("render_error", StatusInternalServerError, func() {
    ContentType("text/html; charset=utf-8")
    Body("body")
})

The server encodes the selected field, and the generated client restores that field on the custom error. With application/json, an Any or map field is encoded directly without an extra object containing the field name. Any values retain their JSON numeric precision. An explicit Body(func() { ... }) continues to describe an object body. Regenerate servers and clients to pick up corrections to selected error bodies.

The generated Error() method returns the first non-empty string field with one of these names:

  1. message
  2. detail
  3. title
  4. error
  5. reason

If these fields are empty or absent, Error() returns the custom type description.

HTTP and JSON-RPC encode the full built-in error as a problem document with type, title, status, detail, instance, code, retry_hint, timeout, temporary and fault. The last three fields are required booleans, including explicit false values. Clients preserve their values independently of HTTP status or JSON-RPC error code. For example, an all-false error mapped to HTTP 500 remains all-false, and Timeout=true does not imply Temporary=true.

Authored body and header/cookie mappings determine which properties are conveyed. An explicitly pruned object body such as Body(func() { Attribute("detail") }) omits the properties; clients use false for each omitted property. Scalar body selection, such as Body("detail"), and Body(Empty) automatically map remaining members to headers. Explicit header and cookie mappings also preserve the selected properties. Custom error types retain their own authored shape.

Regenerate clients and servers together after adopting this contract. Handwritten calls to loomhttp.ProblemErrorFromBody now pass a loomhttp.ProblemResponse value containing the explicit properties; the former five-argument call and status-based inference are removed.

Error Properties

Error properties inform clients about error characteristics (only available with ErrorResult):

var _ = Service("calc", func() {
    Error("service_unavailable", ErrorResult, func() {
        Description("Service is temporarily unavailable")
        Temporary()  // Client should retry
    })

    Error("request_timeout", ErrorResult, func() {
        Description("Request timed out")
        Timeout()    // Deadline exceeded
    })

    Error("internal_error", ErrorResult, func() {
        Description("Internal server error")
        Fault()      // Server-side issue
    })
})

Client-side handling:

res, err := client.Divide(ctx, payload)
if err != nil {
    if e, ok := err.(*loom.ServiceError); ok {
        if e.Temporary {
            return retry(ctx, func() error {
                res, err = client.Divide(ctx, payload)
                return err
            })
        }
        if e.Fault {
            log.Error("server fault detected", "error", e)
            alertAdmins(e)
        }
    }
}

Transport Mapping

HTTP Status Codes

var _ = Service("divider", func() {
    Error("DivByZero", func() {
        Description("Division by zero error")
    })

    HTTP(func() {
        Response("DivByZero", StatusBadRequest)
    })

    Method("integral_divide", func() {
        Error("HasRemainder", func() {
            Description("Integer division has a remainder")
        })

        HTTP(func() {
            POST("/divide/integral")
            Response("HasRemainder", StatusExpectationFailed)
        })
    })
})

gRPC Status Codes

var _ = Service("divider", func() {
    Error("DivByZero", func() {
        Description("Division by zero error")
    })

    GRPC(func() {
        Response("DivByZero", CodeInvalidArgument)
    })

    Method("integral_divide", func() {
        Error("HasRemainder")

        GRPC(func() {
            Response("HasRemainder", CodeUnknown)
        })
    })
})

Combined HTTP and gRPC

var _ = Service("divider", func() {
    Error("DivByZero")

    Method("divide", func() {
        HTTP(func() {
            POST("/divide")
            Response("DivByZero", StatusUnprocessableEntity)
        })

        GRPC(func() {
            Response("DivByZero", CodeInvalidArgument)
        })
    })
})

JSON-RPC Server Diagnostics

The errhandler callback accepted by generated JSON-RPC server constructors and per-method handler constructors is optional and may be nil. When supplied, it runs synchronously at the transport's diagnostic reporting points. Unary handlers report failed notifications and response encoding failures this way. A nil callback skips diagnostic reporting; it does not panic or change the protocol response. Mounted notification handlers suppress any response body written by the callback. The callback's own panics are not recovered.

Regenerate JSON-RPC servers to apply the nil-safe reporting path to generated adapters. Framework runtime and generated code share jsonrpc.ReportFailure; applications normally supply their callback to the generated constructor.

Only a valid JSON-RPC request without an id is a notification. Across HTTP, SSE and WebSocket, an invalid envelope still receives an Invalid Request (-32600) response, with a null ID when none can be recovered. For example, {"jsonrpc":"1.0","method":"echo"} receives an error; a valid {"jsonrpc":"2.0","method":"echo"} suppresses responses, including method and payload errors. Malformed JSON receives Parse Error (-32700). WebSocket request errors leave the connection available for subsequent requests unless sending the response fails. Upgrade the framework runtime to apply this fix; no design change or regeneration is required.

JSON-RPC Error Codes

JSON-RPC errors are mapped with JSONRPC response blocks. Loom includes standard JSON-RPC constants such as RPCInvalidParams and RPCInternalError, and custom application errors can use implementation-defined codes.

var _ = Service("divider", func() {
    Error("DivByZero")

    JSONRPC(func() {
        POST("/jsonrpc")
        Response("DivByZero", RPCInvalidParams)
    })

    Method("divide", func() {
        JSONRPC(func() {})
    })
})

The effective JSON-RPC mapping selects the error.data schema:

  • An explicit JSON-RPC Response(...) mapping uses the designed error body. The server projects the concrete service error into that body. The generated client validates the same body and reconstructs the service error. SSE uses the same mapping when the endpoint returns an error or calls SendError. Regenerate servers and clients after upgrading to correct previously bypassed SSE endpoint mappings and built-in error source generation.
  • A shared custom error type must include a required ErrorName field when two error names use that type. The field distinguishes errors that share one numeric JSON-RPC code.
  • Unary, SSE and WebSocket clients reconstruct mapped errors through the same selection rules. They use the actual ErrorName JSON key (including mappings and full tags), or the root string when Body selects that field. An ordinary field called name does not replace the declared discriminator. Missing, null or unknown discriminator values are invalid responses; defaults do not supply a missing identity.
  • When several errors share a numeric code, exactly one designed body must match its selector, decoding and validation contract. Distinct JSON types and disjoint constraints can distinguish alternatives without a discriminator. Identical valid wire representations are ambiguous: expose an identity in the body or assign distinct codes. Clients report ambiguity instead of choosing the first declaration.
  • Each eligible alternative receives private decoding state. A custom decoder failure takes precedence over a successful alternative unless it is a structured JSON conversion mismatch. This classification follows the decoder error contract; arbitrary callback side effects cannot be rolled back. Failed selection preserves underlying decoding and validation causes.
  • An error without an explicit JSON-RPC mapping uses jsonrpc.ErrorData. Generated clients return its raw *jsonrpc.RawErrorResponse envelope.
  • Protocol failures also use the protocol or generic data shape. They never use an application error body.
  • HTTP error mappings apply only to HTTP. Matching error names do not copy an HTTP status code or body schema into JSON-RPC.

Regenerate clients to adopt these shared typed-error rules across transports.


Producing and Consuming Errors

Producing Errors

Using generated helper functions:

func (s *dividerSvc) IntegralDivide(ctx context.Context, p *divider.IntOperands) (int, error) {
    if p.Divisor == 0 {
        return 0, gendivider.MakeDivByZero(fmt.Errorf("divisor cannot be zero"))
    }
    if p.Dividend%p.Divisor != 0 {
        return 0, gendivider.MakeHasRemainder(fmt.Errorf("remainder is %d", p.Dividend%p.Divisor))
    }
    return p.Dividend / p.Divisor, nil
}

Using custom error types:

func (s *dividerSvc) IntegralDivide(ctx context.Context, p *divider.IntOperands) (int, error) {
    if p.Divisor == 0 {
        return 0, &gendivider.DivByZero{
            Name:     "DivByZero",
            Message:  "divisor cannot be zero",
            Dividend: p.Dividend,
        }
    }
    return p.Dividend / p.Divisor, nil
}

Consuming Errors

Handling default errors:

res, err := client.Divide(ctx, payload)
if err != nil {
    if serr, ok := err.(*loom.ServiceError); ok {
        switch serr.Name {
        case "HasRemainder":
            // Handle remainder error
        case "DivByZero":
            // Handle division by zero
        default:
            // Handle unknown errors
        }
    }
}

Handling custom errors:

res, err := client.Divide(ctx, payload)
if err != nil {
    if dbz, ok := err.(*gendivider.DivByZero); ok {
        fmt.Printf("Division by zero: %s (dividend was %d)\n", dbz.Message, dbz.Dividend)
    }
}

Structured Remediation

Use Remedy when a client or operator needs a stable next action in addition to the error classification:

Error("expired_session", ErrorResult, func() {
    Description("The session can no longer authorize requests.")
    Remedy(func() {
        RemedyCode("session.reauthenticate")
        SafeMessage("Your session expired. Sign in again.")
        RetryHint("Obtain a new session before retrying the request.")
    })
})

A remedy must declare at least one field:

  • RemedyCode is a stable machine-facing action or classification. Do not use human prose as the code.
  • SafeMessage is suitable for an end user and replaces internal error detail on default transport error paths.
  • RetryHint tells the caller how or when a retry can succeed; it should not merely repeat that the operation failed.

Generated default-error constructors attach the remedy to the returned *loom.ServiceError. Generated custom error types expose the same metadata through LoomErrorRemedy. Runtime code can consume either shape with loom.ExtractErrorRemedy, loom.ErrorRemedyCode, loom.ErrorSafeMessage, and loom.ErrorRetryHint instead of type-switching on generated errors.

The default HTTP problem document uses SafeMessage as detail and publishes RetryHint as retry_hint. Unmapped JSON-RPC errors carry the full nested remedy object in generic error.data.

Mapped JSON-RPC errors use the designed body instead. Add remedy fields to the custom error type when that public body must expose them. Keep internal causes in wrapped errors and logs. Do not place credentials, queries, or stack traces in any remediation field.

Default transport messages for unknown service errors are internal server error. A ServiceError or generated error owns its public message; SafeMessage overrides that message. Ordinary wrappers contribute server-side diagnostic context but do not add text to the public message. Independent joined failures have a generic public message unless an explicit outer error owns the failure. Encoding leaves the original error and its cause unchanged for server-side diagnosis.

HTTP and JSON-RPC also resolve one owner for the response code, designed body and metadata. An independent join cannot publish one branch's typed body, name, ID, retry flags, mapped headers or cookies. An explicit outer named error owns the complete response; an inner concrete error cannot supply its body, even when both errors have the same name. Ordinary wrappers and joins containing only one nonnil error preserve the underlying contract. A wrapper supplying only a safe message or remedy does not replace that typed owner. A nil remedy on an outer remedier shadows inner remediation metadata.

Regenerate server adapters after upgrading to adopt complete response ownership in mapped HTTP, JSON-RPC unary/SSE/WebSocket and generated gRPC error conversion. Default runtime encoders adopt the correction on upgrade. Diagnostic helpers such as ExtractErrorRemedy still inspect error trees for their standalone uses; wire encoding bounds metadata lookup to the resolved response. Custom HTTP formatters receive the original error, including wrappers, and remain responsible for the public data they choose to expose.

gRPC applies this policy to both the default status message and error detail, including safe messages in validation history. Its status codes and designed typed details retain their protocol contracts. Native cancellation and deadline errors use canonical context messages with no synthetic service detail. An explicit gRPC status remains an authored public response. Custom error bodies remain public data chosen by the design.

This correction is in shared runtime code; existing generated default error encoders receive it when the application upgrades Loom. Regeneration is not required for this message change.


Default HTTP Problem Documents

When an HTTP endpoint returns a default Loom service error, Loom serializes it as an RFC 9457 problem document using application/problem+json.

The default problem body contains:

  • type: a URI identifying the problem category
  • title: a short human-readable title
  • status: the HTTP status code
  • detail: a safe message for this occurrence
  • instance: a stable urn:loom:error:<id> occurrence identifier
  • code: the stable Loom error name
  • retry_hint: optional retry or correction guidance

Generic HTTP problems use about:blank when the error code matches the status. Other errors get deterministic Loom problem type URIs such as https://github.com/CaliLuke/loom/problems/div-by-zero.

After routes are registered, the default HTTP muxer's JSON, XML, and Gob responses for unmatched paths have HTTP status and body status both set to 404, code: "not_found", type: "about:blank", and title: "Not Found". This routing fallback uses ResponseEncoder negotiation: JSON by default, or XML or Gob when requested through Accept. For text/plain and text/html, it returns status 404 with the public message 404 page not found as the body.

Override the generated problem type or title in the error DSL:

Error("wrong_token_type", ErrorResult, func() {
    ProblemType("https://example.com/problems/wrong-token-type")
    ProblemTitle("Wrong Token Type")
})

Identifier Entropy Failures

Loom never substitutes partial bytes or a zero identifier when the operating system's cryptographic entropy source fails. APIs that already return only a string — including framework-generated service-error, request-log, and trace identifiers — fail loudly because they cannot report the failure in their signature. Treat such a panic as a process-level environment failure, not a recoverable request condition.

Generated JSON-RPC clients have an error-returning encoding path. If generation of an automatic request ID fails, the client returns a wrapped encoding error and does not send a request with a missing, partial, or zero ID.

Custom Error Serialization

Customize error serialization by providing a custom formatter:

type CustomErrorResponse struct {
    Code    string            `json:"code"`
    Message string            `json:"message"`
    Details map[string]string `json:"details,omitempty"`
}

func (r *CustomErrorResponse) StatusCode() int {
    switch r.Code {
    case "VALIDATION_ERROR":
        return http.StatusBadRequest
    case "NOT_FOUND":
        return http.StatusNotFound
    default:
        return http.StatusInternalServerError
    }
}

func customErrorFormatter(ctx context.Context, err error) loomhttp.StatusCoder {
    if serr, ok := err.(*loom.ServiceError); ok {
        switch serr.Name {
        case loom.MissingField:
            return &CustomErrorResponse{
                Code:    "MISSING_FIELD",
                Message: fmt.Sprintf("The field '%s' is required", *serr.Field),
                Details: map[string]string{"field": *serr.Field},
            }
        default:
            return &CustomErrorResponse{
                Code:    "VALIDATION_ERROR",
                Message: serr.Message,
            }
        }
    }
    return &CustomErrorResponse{
        Code:    "INTERNAL_ERROR",
        Message: err.Error(),
    }
}

// Use when creating the server
server = calcsvr.New(endpoints, mux, dec, enc, eh, customErrorFormatter)

Best Practices

1. Consistent Error Naming

Use clear, descriptive names:

// Good
Error("DivByZero", func() {
    Description("DivByZero is returned when the divisor is zero.")
})

// Bad
Error("Error1", func() {
    Description("An unspecified error occurred.")
})

2. Prefer ErrorResult Over Custom Types

Use the default ErrorResult for most errors. Reserve custom types for scenarios requiring additional context:

// Simple errors - use ErrorResult
Error("InvalidInput", ErrorResult, "Invalid input provided.")

// Complex errors needing extra context - use custom types
Error("InvalidOperation", InvalidOperation, "Unsupported operation.")

3. Use Error Properties

Leverage Temporary(), Timeout(), and Fault() to provide metadata:

Error("ServiceUnavailable", ErrorResult, func() {
    Description("Service is temporarily unavailable")
    Temporary()
})

4. Document Errors Thoroughly

Provide clear descriptions:

Error("AuthenticationFailed", ErrorResult, func() {
    Description("AuthenticationFailed is returned when user credentials are invalid.")
})

5. Implement Proper Error Mapping

Map errors consistently across transports:

var _ = Service("auth", func() {
    Error("InvalidToken", func() {
        Description("InvalidToken is returned when the provided token is invalid.")
    })

    HTTP(func() {
        Response("InvalidToken", StatusUnauthorized)
    })

    GRPC(func() {
        Response("InvalidToken", CodeUnauthenticated)
    })
})

6. Test Error Handling

Write tests to verify error behavior:

func TestDivideByZero(t *testing.T) {
    svc := internal.NewDividerService()
    _, err := svc.Divide(context.Background(), &divider.DividePayload{A: 10, B: 0})
    if err == nil {
        t.Fatalf("expected error, got nil")
    }
    if serr, ok := err.(*loom.ServiceError); !ok || serr.Name != "DivByZero" {
        t.Fatalf("expected DivByZero error, got %v", err)
    }
}

7. Security Considerations

  • Never expose internal system details in errors
  • Sanitize all error messages
  • Log detailed errors internally but return safe messages to clients
func secureErrorFormatter(ctx context.Context, err error) loomhttp.StatusCoder {
    log.Printf("Error: %+v", err)  // Log full details
    
    if serr, ok := err.(*loom.ServiceError); ok && serr.Fault {
        // Return generic message for server faults
        return &CustomErrorResponse{
            Code:    "INTERNAL_ERROR",
            Message: "An internal error occurred",
        }
    }
    // Return specific message for validation errors
    return formatValidationError(err)
}

See Also