finished up the shell error formats and result objects along with their corresponding helper factories

This commit is contained in:
2026-07-28 05:43:19 +02:00
parent b9a27cea2a
commit 3b50214041
2 changed files with 263 additions and 13 deletions
+223
View File
@@ -0,0 +1,223 @@
export interface ShellError {
readonly errorType: string;
readonly message: string;
readonly timestamp: number;
readonly exitCode: number;
readonly cause?: {
readonly name: string;
readonly message: string;
};
}
export function createShellError<E extends ShellError>(
errorType: E["errorType"],
message: string,
extraProps: Omit<E, keyof ShellError>,
cause?: { name: string; message: string },
): E {
let exitCode = EXIT_CODE_MAP[errorType] ?? 1;
// Special handling for signal termination
if (errorType === "SIGNAL_TERMINATION") {
const signalError = extraProps as unknown as { signalNumber: number };
exitCode = 128 + signalError.signalNumber;
}
const base: ShellError = Object.freeze({
errorType,
message,
timestamp: Date.now(),
exitCode,
...Object.freeze(cause !== undefined && { cause }),
});
return Object.freeze({ ...base, ...extraProps }) as E;
}
const EXIT_CODE_MAP: Record<string, number> = {
GenericError: 1,
InvalidArguments: 2,
UsageError: 63,
PathResolutionError: 64,
DataFormatError: 65,
FileNotFound: 66,
UserNotFound: 67,
HostNotFound: 68,
ServiceUnavailable: 69,
InternalSoftwareError: 70,
OperatingSystemError: 71,
SystemFileError: 72,
CannotCreateOutput: 73,
IoError: 74,
TemporaryFailure: 75,
TimeoutError: 75, // Same as TEMPFAIL
ProtocolError: 76,
PermissionDenied: 77,
ConfigurationError: 78,
CommandNotFound: 127,
NotExecutable: 126,
// SIGNAL_TERMINATION is handled dynamically (128 + signal)
};
/** Generic catch-all error (Exit 1) */
// Its actually the ShellError itself - no need for a custom type
/* export interface GenericError extends ShellError {
errorType: "GENERIC_ERROR";
} */
export interface InvalidArgumentsError extends ShellError {
errorType: "InvalidArguments";
expected: string; // e.g., "Usage: command <file>"
actual: string; // e.g., the user's input
}
// Codes 3 - 63 reserved for currently running processes, and their specific error handling.
/** Command used incorrectly (bad flag, wrong arg count) - maps to EX_USAGE (Exit 64) */
export interface UsageError extends ShellError {
errorType: "UsageError";
usageHint: string; // e.g., "command [-a] [-b] <filename>"
}
// ===================== 2. FILE / I/O ERRORS (Exit: 65, 66, 72, 73, 74) =====================
/** Input file does not exist or is unreadable (Exit 66 - EX_NOINPUT) */
export interface FileNotFoundError extends ShellError {
errorType: "FileNotFound";
path: string;
}
export interface PathResolutionError extends ShellError {
errorType: "PathResolutionError";
path: string;
}
/** Input data has invalid format (Exit 65 - EX_DATAERR) */
export interface DataFormatError extends ShellError {
errorType: "DataFormatError";
path?: string; // Optional: which file had bad data
line?: number; // Optional: line number if applicable
}
/** System file (e.g., /etc/passwd, /etc/hosts) is broken or missing (Exit 72 - EX_OSFILE) */
export interface SystemFileError extends ShellError {
errorType: "SystemFileError";
path: string;
}
/** Cannot create user-specified output file (Exit 73 - EX_CANTCREAT) */
export interface CannotCreateOutputError extends ShellError {
errorType: "CannotCreateOutput";
path: string;
reason: string; // e.g., "Directory does not exist", "Read-only filesystem"
}
/** I/O error while reading/writing a file (Exit 74 - EX_IOERR) */
export interface IOError extends ShellError {
errorType: "IoError";
path: string;
operation: "read" | "write" | "seek";
}
// ===================== 3. PERMISSION / USER ERRORS (Exit: 67, 77) =====================
/** Insufficient permission to access a resource (Exit 77 - EX_NOPERM) */
export interface PermissionDeniedError extends ShellError {
errorType: "PermissionDenied";
resource: string; // File path, port, socket, etc.
}
/** Specified user does not exist (Exit 67 - EX_NOUSER) */
export interface UserNotFoundError extends ShellError {
errorType: "UserNotFound";
username: string;
}
// ===================== 4. NETWORK / HOST / SERVICE ERRORS (Exit: 68, 69) =====================
/** Specified host does not exist or is unreachable (Exit 68 - EX_NOHOST) */
export interface HostNotFoundError extends ShellError {
errorType: "HostNotFound";
hostname: string;
}
/** Required service is unavailable (Exit 69 - EX_UNAVAILABLE) */
export interface ServiceUnavailableError extends ShellError {
errorType: "ServiceUnavailable";
service: string; // e.g., "database", "DNS", "SSH"
port?: number;
}
// ===================== 5. PROCESS / EXECUTION ERRORS (Exit: 126, 127, 71) =====================
/** Command not found (Exit 127 - POSIX standard) */
export interface CommandNotFoundError extends ShellError {
errorType: "CommandNotFound";
command: string;
}
/** Command found but not executable (Exit 126 - POSIX standard) */
export interface NotExecutableError extends ShellError {
errorType: "NotExecutable";
path: string;
}
/** Operating system error (fork, pipe, process table full) (Exit 71 - EX_OSERR) */
export interface OperatingSystemError extends ShellError {
errorType: "OperatingSystemError";
syscall: string; // e.g., "fork", "pipe", "execve"
errno?: number; // Optional: underlying OS error code
}
// ===================== 6. TIMING / RETRY ERRORS (Exit: 75) =====================
/** Temporary failure; user should retry (Exit 75 - EX_TEMPFAIL) */
export interface TemporaryFailureError extends ShellError {
errorType: "TemporaryFailure";
retryAfter?: number; // Optional: recommended seconds to wait
resource?: string; // Optional: what resource is temporarily busy
}
/** Operation timed out (Often mapped to EX_TEMPFAIL, Exit 75) */
export interface TimeoutError extends ShellError {
errorType: "TimeoutError";
timeoutSeconds: number;
operation: string; // e.g., "HTTP request", "Database query"
}
// ===================== 7. INTERNAL / CONFIGURATION ERRORS (Exit: 70, 78) =====================
/** Internal software error (bug, assertion failed) (Exit 70 - EX_SOFTWARE) */
export interface InternalSoftwareError extends ShellError {
errorType: "InternalSoftwareError";
component: string; // e.g., "parser", "network layer"
}
/** Configuration error in the program or system (Exit 78 - EX_CONFIG) */
export interface ConfigurationError extends ShellError {
errorType: "ConfigurationError";
configFile?: string;
key?: string; // Which config key is wrong
}
// ===================== 8. PROTOCOL / REMOTE ERRORS (Exit: 76) =====================
/** Remote system protocol error (Exit 76 - EX_PROTOCOL) */
export interface ProtocolError extends ShellError {
errorType: "ProtocolError";
remoteHost?: string;
protocol: string; // e.g., "HTTP", "SSH", "FTP"
statusCode?: number; // Optional: e.g., HTTP 400/500
}
// ===================== 9. SIGNAL TERMINATION (Exit: 128 + signal) =====================
/** Process was killed by a signal (Exit = 128 + signalNumber) */
export interface SignalTerminationError extends ShellError {
errorType: "SignalTermination";
signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT)
signalName: string; // e.g., "SIGTERM", "SIGKILL"
}
+40 -13
View File
@@ -1,18 +1,8 @@
import type { ImmutableBuffer } from "./util/immutable_buffer"; import { createShellError, type ShellError } from "./errors";
import { createImmutableBuffer, type ImmutableBuffer } from "./util/immutable_buffer";
export interface ShellError {
readonly errorType: string;
readonly message: string;
readonly timestamp: number;
readonly cause?: {
readonly name: string;
readonly message: string;
};
}
export interface ResultError<E extends ShellError> { export interface ResultError<E extends ShellError> {
readonly type: "error"; readonly type: "error";
readonly exitCode: number;
readonly stdout: ImmutableBuffer; readonly stdout: ImmutableBuffer;
readonly stderr: ImmutableBuffer; readonly stderr: ImmutableBuffer;
readonly commandName?: string; readonly commandName?: string;
@@ -21,10 +11,47 @@ export interface ResultError<E extends ShellError> {
export interface ResultSuccess { export interface ResultSuccess {
readonly type: "success"; readonly type: "success";
readonly exitCode: number;
readonly stdout: ImmutableBuffer; readonly stdout: ImmutableBuffer;
readonly stderr: ImmutableBuffer; readonly stderr: ImmutableBuffer;
readonly exitCode: number;
readonly commandName?: string; readonly commandName?: string;
} }
export type Result<E extends ShellError> = ResultSuccess | ResultError<E>; export type Result<E extends ShellError> = ResultSuccess | ResultError<E>;
export function createErrorResult<E extends ShellError>(
errorType: E["errorType"],
message: string,
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
extraProps: Omit<E, keyof ShellError>,
stdout: ImmutableBuffer,
stderr: ImmutableBuffer,
commandName?: string,
cause?: { name: string; message: string },
): ResultError<E> {
const error = createShellError<E>(errorType, message, extraProps, cause);
return Object.freeze({
type: "error",
stdout,
stderr,
error,
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
...(commandName !== undefined && { commandName }),
});
}
export function createSuccessResult(
commandName?: string,
exitCode?: number,
stdout?: ImmutableBuffer,
stderr?: ImmutableBuffer,
): ResultSuccess {
return Object.freeze({
type: "success",
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
exitCode: exitCode ?? 0,
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
...(commandName !== undefined && { commandName }),
});
}