CrustError
Typed error class with error codes and structured details.
CrustError is the custom error class used by all Crust framework-level errors. It extends Error with a typed code for programmatic handling.
Properties
| Property | Type | Description |
|---|---|---|
code | CrustErrorCode | Machine-readable error code |
message | string | Human-readable error message |
details | CrustErrorDetails<C> | Structured payload (typed per error code) |
cause | unknown | Optional chained original error |
name | string | Always "CrustError" |
Error Codes
| Code | When Thrown | Details Type |
|---|---|---|
DEFINITION | Invalid command configuration (empty name, alias collision, invalid no- prefixed flag name/alias) | undefined |
VALIDATION | Missing required argument or flag | ValidationErrorDetails | undefined |
PARSE | Argv parsing failure (unknown flag, type coercion) | undefined |
EXECUTION | Runtime command/middleware failure | undefined |
COMMAND_NOT_FOUND | Unknown subcommand | CommandNotFoundErrorDetails |
Methods
.is(code)
Type-narrowing method that checks the error code:
if (error instanceof CrustError) {
if (error.is("COMMAND_NOT_FOUND")) {
// error.details is now CommandNotFoundErrorDetails
console.log(error.details.input);
console.log(error.details.available);
}
if (error.is("VALIDATION")) {
// error.details is ValidationErrorDetails | undefined
console.log(error.message);
if (error.details) {
console.log(error.details.issues);
}
}
}.withCause(cause)
Chains an original error for debugging. Returns this for fluent API:
throw new CrustError("EXECUTION", "Operation failed").withCause(originalError);Creating Errors
Framework Errors
import { CrustError } from "@crustjs/core";
throw new CrustError("VALIDATION", `Invalid value for --port: "${value}"`);With Details
throw new CrustError("COMMAND_NOT_FOUND", `Unknown command "${name}".`, {
input: name,
available: ["build", "dev"],
commandPath: ["my-cli"],
parentCommand: rootCmd,
});With Cause Chain
try {
await riskyOperation();
} catch (err) {
throw new CrustError("EXECUTION", "Operation failed").withCause(err);
}Catching Errors
.execute() catches all errors internally, prints them to stderr, and sets process.exitCode = 1. For programmatic error handling (e.g., in tests), you can catch errors from lower-level functions like parseArgs and resolveCommand:
import { CrustError, parseArgs, resolveCommand } from "@crustjs/core";
try {
const route = resolveCommand(app._node, argv);
const result = parseArgs(route.command, route.argv);
} catch (error) {
if (!(error instanceof CrustError)) throw error;
switch (error.code) {
case "VALIDATION":
console.error(error.message);
break;
case "PARSE":
console.error(error.message);
break;
case "COMMAND_NOT_FOUND":
console.error(`Unknown: ${error.details.input}`);
break;
default:
console.error(`[${error.code}] ${error.message}`);
}
}In plugin middleware, you can also catch and handle errors within the middleware chain. See Plugins for details.