For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt, and this page is available as Markdown at /byethrow/guide/best-practices/custom-error.md.
  • English
  • Custom Error

    Any value can be used as the error of a Result, but plain strings and generic Error objects make it hard for callers to tell failures apart. We strongly recommend giving each kind of failure its own error type. This page explains the options and how to create custom errors efficiently.

    Two Ways to Define Custom Errors

    Define a class that extends the built-in Error class, and give it a unique name:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    import z
    z
    } from 'zod';
    class
    class ValidationError
    ValidationError
    extends
    var Error: ErrorConstructor
    Error
    {
    override readonly
    ValidationError.name: "ValidationError"
    name
    = 'ValidationError';
    } const
    const validateEmail: (email: string) => Result.Result<string, ValidationError>
    validateEmail
    = (
    email: string
    email
    : string):
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const doSomething = (): Result.Result<number, string> => {
      return Math.random() > 0.5
        ? { type: 'Success', value: 10 }
        : { type: 'Failure', error: 'Oops' };
    };
    @categoryCore Types
    Result
    <string,
    class ValidationError
    ValidationError
    > => {
    return
    import Result
    Result
    .
    function pipe<string, Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, Result.Result<string, ValidationError>>(a: string, ab: (a: string) => Result.Result<string, readonly StandardSchemaV1.Issue[]>, bc: (b: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, ValidationError>): Result.Result<string, ValidationError> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    email: string
    email
    ,
    import Result
    Result
    .
    function parse<z.ZodEmail>(schema: z.ZodEmail): (value: unknown) => Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    import z
    z
    .
    function email(params?: string | z.core.$ZodEmailParams): z.ZodEmail
    email
    ()),
    import Result
    Result
    .
    function mapError<Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, ValidationError>(fn: (a: readonly StandardSchemaV1.Issue[]) => ValidationError): (result: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, ValidationError> (+1 overload)

    Applies a transformation function to the error value of a Result or ResultAsync . If the input is a Success , it will be returned unchanged.

    @typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@example

    Failure Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('NotFound'),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Failure', error: Error('NotFound') }
    @example

    Success Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(123),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Success', value: 123 }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    mapError
    ((
    issues: readonly StandardSchemaV1.Issue[]
    issues
    ) => new
    constructor ValidationError(message?: string, options?: ErrorOptions): ValidationError (+1 overload)
    ValidationError
    ('Invalid email format', {
    ErrorOptions.cause?: unknown
    cause
    :
    issues: readonly StandardSchemaV1.Issue[]
    issues
    })),
    ); };

    2. Tagged Objects

    Alternatively, use plain objects with a property that identifies the kind of error:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    import z
    z
    } from 'zod';
    type
    type ValidationError = {
        type: "ValidationError";
        message: string;
        value: string;
    }
    ValidationError
    = {
    type: "ValidationError"
    type
    : 'ValidationError';
    message: string
    message
    : string;
    value: string
    value
    : string;
    }; const
    const validateEmail: (email: string) => Result.Result<string, ValidationError>
    validateEmail
    = (
    email: string
    email
    : string):
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const doSomething = (): Result.Result<number, string> => {
      return Math.random() > 0.5
        ? { type: 'Success', value: 10 }
        : { type: 'Failure', error: 'Oops' };
    };
    @categoryCore Types
    Result
    <string,
    type ValidationError = {
        type: "ValidationError";
        message: string;
        value: string;
    }
    ValidationError
    > => {
    return
    import Result
    Result
    .
    function pipe<string, Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, Result.Result<string, {
        readonly type: "ValidationError";
        readonly message: "Invalid email format";
        readonly value: string;
    }>>(a: string, ab: (a: string) => Result.Result<string, readonly StandardSchemaV1.Issue[]>, bc: (b: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, {
        readonly type: "ValidationError";
        readonly message: "Invalid email format";
        readonly value: string;
    }>): Result.Result<...> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    email: string
    email
    ,
    import Result
    Result
    .
    function parse<z.ZodEmail>(schema: z.ZodEmail): (value: unknown) => Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    import z
    z
    .
    function email(params?: string | z.core.$ZodEmailParams): z.ZodEmail
    email
    ()),
    import Result
    Result
    .
    function mapError<Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, {
        readonly type: "ValidationError";
        readonly message: "Invalid email format";
        readonly value: string;
    }>(fn: (a: readonly StandardSchemaV1.Issue[]) => {
        readonly type: "ValidationError";
        readonly message: "Invalid email format";
        readonly value: string;
    }): (result: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, {
        readonly type: "ValidationError";
        readonly message: "Invalid email format";
        readonly value: string;
    }> (+1 overload)

    Applies a transformation function to the error value of a Result or ResultAsync . If the input is a Success , it will be returned unchanged.

    @typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@example

    Failure Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('NotFound'),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Failure', error: Error('NotFound') }
    @example

    Success Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(123),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Success', value: 123 }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    mapError
    (() => ({
    type: "ValidationError"
    type
    : 'ValidationError',
    message: "Invalid email format"
    message
    : 'Invalid email format',
    value: string
    value
    :
    email: string
    email
    ,
    })), ); };

    Why We Recommend Error Classes

    Both approaches let callers distinguish errors, but error classes have several practical advantages.

    Stack Traces and Error Chaining

    An Error records a stack trace showing where it was created, and the cause option keeps the original error that led to it. Together, they make debugging much easier:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    class
    class DatabaseError
    DatabaseError
    extends
    var Error: ErrorConstructor
    Error
    {
    override readonly
    DatabaseError.name: "DatabaseError"
    name
    = 'DatabaseError';
    } const
    const fetchUser: (id: string) => Result.ResultAsync<User, DatabaseError>
    fetchUser
    = (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    try<() => Promise<User>, DatabaseError>(options: {
        try: () => Promise<User>;
        catch: (error: unknown) => DatabaseError;
    }): Result.ResultAsync<User, DatabaseError> (+3 overloads)
    export try

    Executes a function that may throw and wraps the result in a Result or ResultAsync .

    You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

    @typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA Result or ResultAsync wrapping the function's return value or the caught error.@example

    Sync try-catch

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    try: () => {
    const x = Math.random() * 10 - 5;
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    // result is Result<number, Error>
    @example

    Sync safe

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    safe: true,
    try: () => Math.random() + 1,
    });
    
    // result is Result<number, never>
    @example

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    try: () => fetch('/api/data'),
    catch: (error) => new Error('Fetch failed', { cause: error }),
    });
    
    // result is ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    safe: true,
    try: () => Promise.resolve('ok'),
    });
    
    // result is ResultAsync<string, never>
    @categoryCreators
    try
    ({
    try: () => Promise<User>
    try
    : () =>
    const database: {
        findUser: (id: string) => Promise<User>;
    }
    database
    .
    findUser: (id: string) => Promise<User>
    findUser
    (
    id: string
    id
    ),
    // The stack trace points here, and the original error is kept as `cause`
    catch: (error: unknown) => DatabaseError
    catch
    : (
    error: unknown
    error
    ) => new
    constructor DatabaseError(message?: string, options?: ErrorOptions): DatabaseError (+1 overload)
    DatabaseError
    ('Failed to fetch user', {
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    });

    Compatibility with throw

    Errors in a Result sometimes end up being thrown, for example by unwrap at the boundary of your application. Error monitoring tools and runtimes expect thrown values to be Error instances. A thrown plain object has no stack trace and is often reported poorly.

    Writing error classes by hand quickly becomes repetitive. @praha/error-factory reduces the boilerplate and keeps your errors consistent.

    Installation

    npm
    yarn
    pnpm
    bun
    deno
    npm install @praha/error-factory

    Defining Errors

    Extend the class returned by ErrorFactory. The name becomes a literal type, which lets TypeScript narrow unions of errors by their name:

    import { 
    const ErrorFactory: {
        <Name extends string = string, Message extends string = string, Fields extends ErrorFields = ErrorFields>(props: {
            name?: Name;
            message: Message | ((fields: Fields) => Message);
            fields?: Fields;
        }): ErrorConstructor<Name, Message, Fields>;
        fields<Fields extends ErrorFields>(): Fields;
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    } from '@praha/error-factory';
    class
    class ValidationError
    ValidationError
    extends
    ErrorFactory<"ValidationError", "Invalid input provided", ErrorFields>(props: {
        name?: "ValidationError" | undefined;
        message: "Invalid input provided" | ((fields: ErrorFields) => "Invalid input provided");
        fields?: ErrorFields | undefined;
    }): (new (options?: ErrorOptions) => Error & Readonly<{
        name: "ValidationError";
        message: "Invalid input provided";
    }>) & {
        name: "ValidationError";
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    ({
    name?: "ValidationError" | undefined
    name
    : 'ValidationError',
    message: "Invalid input provided" | ((fields: ErrorFields) => "Invalid input provided")
    message
    : 'Invalid input provided',
    }) {} class
    class QueryError
    QueryError
    extends
    ErrorFactory<"QueryError", "An error occurred while executing a query", {
        query: string;
    }>(props: {
        name?: "QueryError" | undefined;
        message: "An error occurred while executing a query" | ((fields: {
            query: string;
        }) => "An error occurred while executing a query");
        fields?: {
            query: string;
        } | undefined;
    }): (new (options: ErrorOptions & {
        query: string;
    }) => Error & Readonly<{
        name: "QueryError";
        message: "An error occurred while executing a query";
    }> & Readonly<{
        query: string;
    }>) & {
        name: "QueryError";
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    ({
    name?: "QueryError" | undefined
    name
    : 'QueryError',
    message: "An error occurred while executing a query" | ((fields: {
        query: string;
    }) => "An error occurred while executing a query")
    message
    : 'An error occurred while executing a query',
    // Additional fields carried by the error
    fields?: {
        query: string;
    } | undefined
    fields
    :
    const ErrorFactory: {
        <Name extends string = string, Message extends string = string, Fields extends ErrorFields = ErrorFields>(props: {
            name?: Name;
            message: Message | ((fields: Fields) => Message);
            fields?: Fields;
        }): ErrorConstructor<Name, Message, Fields>;
        fields<Fields extends ErrorFields>(): Fields;
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    .
    fields<{
        query: string;
    }>(): {
        query: string;
    }
    fields
    <{
    query: string
    query
    : string }>(),
    }) {} class
    class NotFoundError
    NotFoundError
    extends
    ErrorFactory<"NotFoundError", "Resource not found", ErrorFields>(props: {
        name?: "NotFoundError" | undefined;
        message: "Resource not found" | ((fields: ErrorFields) => "Resource not found");
        fields?: ErrorFields | undefined;
    }): (new (options?: ErrorOptions) => Error & Readonly<{
        name: "NotFoundError";
        message: "Resource not found";
    }>) & {
        name: "NotFoundError";
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    ({
    name?: "NotFoundError" | undefined
    name
    : 'NotFoundError',
    message: "Resource not found" | ((fields: ErrorFields) => "Resource not found")
    message
    : 'Resource not found',
    }) {}

    message can also be a function that builds the message from the fields:

    import { 
    const ErrorFactory: {
        <Name extends string = string, Message extends string = string, Fields extends ErrorFields = ErrorFields>(props: {
            name?: Name;
            message: Message | ((fields: Fields) => Message);
            fields?: Fields;
        }): ErrorConstructor<Name, Message, Fields>;
        fields<Fields extends ErrorFields>(): Fields;
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    } from '@praha/error-factory';
    class
    class HttpError
    HttpError
    extends
    ErrorFactory<"HttpError", `Request failed with status ${number}`, {
        status: number;
    }>(props: {
        name?: "HttpError" | undefined;
        message: `Request failed with status ${number}` | ((fields: {
            status: number;
        }) => `Request failed with status ${number}`);
        fields?: {
            status: number;
        } | undefined;
    }): (new (options: ErrorOptions & {
        status: number;
    }) => Error & Readonly<{
        name: "HttpError";
        message: `Request failed with status ${number}`;
    }> & Readonly<{
        status: number;
    }>) & {
        name: "HttpError";
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    ({
    name?: "HttpError" | undefined
    name
    : 'HttpError',
    message: `Request failed with status ${number}` | ((fields: {
        status: number;
    }) => `Request failed with status ${number}`)
    message
    : ({
    status: number
    status
    }) => `Request failed with status ${
    status: number
    status
    }`,
    fields?: {
        status: number;
    } | undefined
    fields
    :
    const ErrorFactory: {
        <Name extends string = string, Message extends string = string, Fields extends ErrorFields = ErrorFields>(props: {
            name?: Name;
            message: Message | ((fields: Fields) => Message);
            fields?: Fields;
        }): ErrorConstructor<Name, Message, Fields>;
        fields<Fields extends ErrorFields>(): Fields;
    }

    A factory function that creates a base class for custom error types.

    Extend the returned class to define a custom error with a consistent structure, reducing boilerplate and ensuring type safety across your application.

    @typeParamName - Inferred as a string literal type from props.name when provided, or defaults to string when name is omitted.@typeParamMessage - Inferred as a string literal type from props.message when it is a string, or defaults to string when message is a function.@typeParamFields - Inferred from props.fields (via ErrorFactory.fields). Defaults to the base ErrorFields constraint when fields is omitted.@paramprops - Configuration for the error class.@paramprops .name - The value set as the name property on both the class and each instance. When omitted, name is inferred as string and set to new.target.name at construction time, which resolves to the name of the concrete subclass. Note that omitting name disables type narrowing via the name property; use name explicitly or instanceof for narrowing.@paramprops .message - The error message. Can be a static string or a function that receives the custom fields and returns a string, enabling dynamic message generation.@paramprops .fields - A type-level placeholder that declares the additional fields the error instance will carry. Use ErrorFactory.fields to create this value. When omitted, no additional fields are added to the instance.@returnsAn abstract base class typed as ErrorConstructor that should be extended to produce a concrete custom error class.@example

    Basic usage

    class NotFoundError extends ErrorFactory({
    name: 'NotFoundError',
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name);    // "NotFoundError"
    console.error(error.message); // "Resource not found"
    @example

    Omitting name

    class NotFoundError extends ErrorFactory({
    message: 'Resource not found',
    }) {}
    
    const error = new NotFoundError();
    console.error(error.name); // "NotFoundError" (resolved from new.target.name)
    @example

    With cause

    class DatabaseError extends ErrorFactory({
    name: 'DatabaseError',
    message: 'A database error occurred',
    }) {}
    
    const error = new DatabaseError({ cause: new Error('Connection failed') });
    console.error(error.cause); // Error: Connection failed
    @example

    With additional fields

    class QueryError extends ErrorFactory({
    name: 'QueryError',
    message: 'An error occurred while executing a query',
    fields: ErrorFactory.fields<{ query: string }>(),
    }) {}
    
    const error = new QueryError({ query: 'SELECT * FROM users' });
    console.error(error.query); // "SELECT * FROM users"
    @example

    Dynamic message

    class ValidationError extends ErrorFactory({
    name: 'ValidationError',
    message: ({ field }) => `Validation failed for field '${field}'`,
    fields: ErrorFactory.fields<{ field: string }>(),
    }) {}
    
    const error = new ValidationError({ field: 'email' });
    console.error(error.message); // "Validation failed for field 'email'"
    ErrorFactory
    .
    fields<{
        status: number;
    }>(): {
        status: number;
    }
    fields
    <{
    status: number
    status
    : number }>(),
    }) {}

    Using Errors in Results

    Create the errors wherever a failure occurs, passing the original error as cause and filling in any fields:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    import z
    z
    } from 'zod';
    const
    const validateId: (id: string) => Result.Result<string, ValidationError>
    validateId
    = (
    id: string
    id
    : string) => {
    return
    import Result
    Result
    .
    function pipe<string, Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, Result.Result<string, ValidationError>>(a: string, ab: (a: string) => Result.Result<string, readonly StandardSchemaV1.Issue[]>, bc: (b: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, ValidationError>): Result.Result<string, ValidationError> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    id: string
    id
    ,
    import Result
    Result
    .
    function parse<z.ZodString>(schema: z.ZodString): (value: unknown) => Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    import z
    z
    .
    function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)
    string
    ().
    _ZodString<$ZodStringInternals<string>>.startsWith(value: string, params?: string | z.core.$ZodCheckStartsWithParams): z.ZodString
    startsWith
    ('u')),
    import Result
    Result
    .
    function mapError<Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, ValidationError>(fn: (a: readonly StandardSchemaV1.Issue[]) => ValidationError): (result: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, ValidationError> (+1 overload)

    Applies a transformation function to the error value of a Result or ResultAsync . If the input is a Success , it will be returned unchanged.

    @typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@example

    Failure Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('NotFound'),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Failure', error: Error('NotFound') }
    @example

    Success Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(123),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Success', value: 123 }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    mapError
    ((
    issues: readonly StandardSchemaV1.Issue[]
    issues
    ) => new
    constructor ValidationError(options?: ErrorOptions): ValidationError
    ValidationError
    ({
    ErrorOptions.cause?: unknown
    cause
    :
    issues: readonly StandardSchemaV1.Issue[]
    issues
    })),
    ); }; const
    const executeQuery: (sql: string, params: unknown[]) => Result.ResultAsync<UserRow | undefined, QueryError>
    executeQuery
    = (
    sql: string
    sql
    : string,
    params: unknown[]
    params
    : unknown[]) => {
    return
    import Result
    Result
    .
    try<() => Promise<UserRow | undefined>, QueryError>(options: {
        try: () => Promise<UserRow | undefined>;
        catch: (error: unknown) => QueryError;
    }): Result.ResultAsync<UserRow | undefined, QueryError> (+3 overloads)
    export try

    Executes a function that may throw and wraps the result in a Result or ResultAsync .

    You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

    @typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA Result or ResultAsync wrapping the function's return value or the caught error.@example

    Sync try-catch

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    try: () => {
    const x = Math.random() * 10 - 5;
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    // result is Result<number, Error>
    @example

    Sync safe

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    safe: true,
    try: () => Math.random() + 1,
    });
    
    // result is Result<number, never>
    @example

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    try: () => fetch('/api/data'),
    catch: (error) => new Error('Fetch failed', { cause: error }),
    });
    
    // result is ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const result = Result.try({
    safe: true,
    try: () => Promise.resolve('ok'),
    });
    
    // result is ResultAsync<string, never>
    @categoryCreators
    try
    ({
    try: () => Promise<UserRow | undefined>
    try
    : () =>
    const database: {
        query: (sql: string, params: unknown[]) => Promise<UserRow | undefined>;
    }
    database
    .
    query: (sql: string, params: unknown[]) => Promise<UserRow | undefined>
    query
    (
    sql: string
    sql
    ,
    params: unknown[]
    params
    ),
    catch: (error: unknown) => QueryError
    catch
    : (
    error: unknown
    error
    ) => new
    constructor QueryError(options: ErrorOptions & {
        query: string;
    }): QueryError
    QueryError
    ({
    query: string
    query
    :
    sql: string
    sql
    ,
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    }); }; const
    const findUser: (id: string) => Result.ResultAsync<{
        readonly id: string;
        readonly name: string;
    }, ValidationError | QueryError | NotFoundError>
    findUser
    = (
    id: string
    id
    : string) => {
    return
    import Result
    Result
    .
    function pipe<Result.Result<string, ValidationError>, Result.ResultAsync<UserRow | undefined, ValidationError | QueryError>, Result.ResultAsync<{
        readonly id: string;
        readonly name: string;
    }, ValidationError | QueryError | NotFoundError>>(a: Result.Result<string, ValidationError>, ab: (a: Result.Result<string, ValidationError>) => Result.ResultAsync<UserRow | undefined, ValidationError | QueryError>, bc: (b: Result.ResultAsync<...>) => Result.ResultAsync<...>): Result.ResultAsync<...> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    const validateId: (id: string) => Result.Result<string, ValidationError>
    validateId
    (
    id: string
    id
    ),
    import Result
    Result
    .
    function andThen<Result.Result<string, ValidationError>, Result.ResultAsync<UserRow | undefined, QueryError>>(fn: (a: string) => Result.ResultAsync<UserRow | undefined, QueryError>): (result: Result.Result<string, ValidationError>) => Result.ResultAsync<UserRow | undefined, ValidationError | QueryError> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    ((
    id: string
    id
    ) =>
    const executeQuery: (sql: string, params: unknown[]) => Result.ResultAsync<UserRow | undefined, QueryError>
    executeQuery
    ('SELECT * FROM users WHERE id = ?', [
    id: string
    id
    ])),
    import Result
    Result
    .
    function andThen<Result.ResultAsync<UserRow | undefined, ValidationError | QueryError>, Result.Failure<NotFoundError> | Result.Success<{
        readonly id: string;
        readonly name: string;
    }>>(fn: (a: UserRow | undefined) => Result.Failure<NotFoundError> | Result.Success<{
        readonly id: string;
        readonly name: string;
    }>): (result: Result.ResultAsync<UserRow | undefined, ValidationError | QueryError>) => Result.ResultAsync<...> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    ((
    row: UserRow | undefined
    row
    ) => {
    if (!
    row: UserRow | undefined
    row
    ) {
    return
    import Result
    Result
    .
    function fail<NotFoundError>(error: NotFoundError): Result.Result<never, NotFoundError> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (new
    constructor NotFoundError(options?: ErrorOptions): NotFoundError
    NotFoundError
    ());
    } return
    import Result
    Result
    .
    function succeed<{
        readonly id: string;
        readonly name: string;
    }>(value: {
        readonly id: string;
        readonly name: string;
    }): Result.Result<{
        readonly id: string;
        readonly name: string;
    }, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    ({
    id: string
    id
    :
    row: UserRow
    row
    .
    id: string
    id
    ,
    name: string
    name
    :
    row: UserRow
    row
    .
    name: string
    name
    });
    }), ); }; // Type: (id: string) => Result.ResultAsync<{ id: string; name: string }, ValidationError | QueryError | NotFoundError>

    Handling Errors

    Because each error has a literal name, a switch statement narrows the error to its exact class, including its fields:

    const 
    const result: Result.Result<{
        id: string;
        name: string;
    }, ValidationError | QueryError | NotFoundError>
    result
    = await
    const findUser: (id: string) => Result.ResultAsync<{
        id: string;
        name: string;
    }, ValidationError | QueryError | NotFoundError>
    findUser
    ('u123');
    if (
    import Result
    Result
    .
    function isSuccess<Result.Result<{
        id: string;
        name: string;
    }, ValidationError | QueryError | NotFoundError>>(result: Result.Result<{
        id: string;
        name: string;
    }, ValidationError | QueryError | NotFoundError>): result is Result.Success<{
        id: string;
        name: string;
    }>

    Type guard to check if a Result is a Success .

    @typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@example
    import { Result } from '@praha/byethrow';
    
    const result: Result.Result<number, string> = { type: 'Success', value: 10 };
    if (Result.isSuccess(result)) {
      console.log(result.value); // Safe access to value
    }
    @categoryType Guards
    isSuccess
    (
    const result: Result.Result<{
        id: string;
        name: string;
    }, ValidationError | QueryError | NotFoundError>
    result
    )) {
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    (
    const result: Result.Success<{
        id: string;
        name: string;
    }>
    result
    .
    value: {
        id: string;
        name: string;
    }
    value
    );
    } else { switch (
    const result: Result.Failure<ValidationError | QueryError | NotFoundError>
    result
    .
    error: ValidationError | QueryError | NotFoundError
    error
    .
    Error.name: "ValidationError" | "QueryError" | "NotFoundError"
    name
    ) {
    case 'ValidationError':
    var console: Console
    console
    .
    Console.error(...data: any[]): void

    The console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.

    MDN Reference

    error
    ('Validation error:',
    const result: Result.Failure<ValidationError | QueryError | NotFoundError>
    result
    .
    error: ValidationError
    error
    .
    Error.message: "Invalid input provided"
    message
    );
    break; case 'QueryError': // Narrowed to QueryError, so `query` is available
    var console: Console
    console
    .
    Console.error(...data: any[]): void

    The console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.

    MDN Reference

    error
    ('Query error:',
    const result: Result.Failure<ValidationError | QueryError | NotFoundError>
    result
    .
    error: QueryError
    error
    .
    Error.message: "An error occurred while executing a query"
    message
    , 'Query:',
    const result: Result.Failure<ValidationError | QueryError | NotFoundError>
    result
    .
    error: QueryError
    error
    .
    query: string
    query
    );
    break; case 'NotFoundError':
    var console: Console
    console
    .
    Console.error(...data: any[]): void

    The console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.

    MDN Reference

    error
    ('Not found error:',
    const result: Result.Failure<ValidationError | QueryError | NotFoundError>
    result
    .
    error: NotFoundError
    error
    .
    Error.message: "Resource not found"
    message
    );
    break; } }

    For more ways to handle unions of errors, including exhaustiveness checks, see Pattern Matching.