Error Handling
Grounds uses neverthrow for type-safe error handling.
Handling Errors with .match()
The .match() method provides exhaustive handling of success and error cases:
// examples/core/encode-error.ts
// Demonstrates: Handling encoding errors with .match() and .mapErr()
import { encode, Struct, String_ } from "@grounds/core";
// Attempt to encode a struct with an invalid field ID (>= 128)
// The Relish wire format requires field IDs to have bit 7 clear (0-127)
const invalidStruct = Struct(new Map([[128, String_("This field ID is invalid")]]));
const result = encode(invalidStruct);
// Use .match() to inspect the error
result.match(
(bytes) => {
console.log("Unexpected success:", bytes);
},
(err) => {
console.log("Expected error occurred!");
console.log("Error message:", err.message);
},
);
// Use .mapErr() to add context to errors
const contextualResult = encode(invalidStruct).mapErr((err) => ({
originalMessage: err.message,
context: "Failed while encoding user profile struct",
}));
contextualResult.match(
() => {},
(err) => {
console.log("\nWith added context:");
console.log("Context:", err.context);
console.log("Original message:", err.originalMessage);
},
);
Error Types
EncodeError
Thrown when encoding fails:
code- Error code string (e.g., “OVERFLOW”, “INVALID_TYPE”)message- Human-readable error description
DecodeError
Thrown when decoding fails:
code- Error code string (e.g., “UNEXPECTED_EOF”, “INVALID_TYPE_CODE”)message- Human-readable error description
Adding Context with .mapErr()
Use .mapErr() to add context to errors without changing the error type:
encode(value)
.mapErr((err) => ({
...err,
context: "Failed while encoding user profile",
}))
.match(
(bytes) => {
/* success */
},
(err) => console.error(err.context, "-", err.message),
);
Chaining with .andThen()
When chaining operations, errors propagate automatically:
encode(value)
.andThen((bytes) => decode(bytes)) // skipped if encode fails
.match(
(decoded) => console.log("Success:", decoded),
(err) => console.error("Failed:", err.message),
);
Next Steps
Ready for type-safe schemas? Continue to Schema Structs.