For AI agents: the complete documentation index is available at /byethrow/ja/llms.txt, the full documentation bundle is available at /byethrow/ja/llms-full.txt, and this page is available as Markdown at /byethrow/ja/guide/best-practices/result-vs-throw.md.
  • 日本語
  • Result vs throw

    「JavaScript はどこでも例外を投げる可能性があり、すべてのエラーを Result で管理することは不可能なので、Result を導入する意味はない」という意見を耳にしたことがあるかもしれません。

    私たちはそうは考えていません。重要なのは、Result が表すべきなのは想定内のエラーだけだということです。 起こりうるすべてのエラーを Result で包む必要はありません。

    想定内のエラーと想定外のエラー

    エラーを Result で表すべきか、throw すべきかは、そのエラーの性質によって決まります。

    想定内のエラー:Result を使う

    想定内のエラーは、アプリケーションのビジネスロジックの一部です。 通常の運用の中で起こることが想定されており、呼び出し側はユーザーにメッセージを表示したり 404 レスポンスを返したりといった、意味のある対応ができます。

    • リクエストされた投稿が存在しない
    • ユーザーがその操作を行う権限を持っていない
    • 送信されたフォームに不正な値が含まれている

    これらのエラーは戻り値の型で表し、呼び出し側が必ず処理するようにします。

    type 
    type PostDeleteError = PostNotFoundError | PostPermissionError | PostAlreadyDeletedError
    PostDeleteError
    = (
    |
    class PostNotFoundError
    PostNotFoundError
    |
    class PostPermissionError
    PostPermissionError
    |
    class PostAlreadyDeletedError
    PostAlreadyDeletedError
    ); const
    const deletePost: (postId: string) => Result.ResultAsync<void, PostDeleteError>
    deletePost
    = async (
    postId: string
    postId
    : string):
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <void,
    type PostDeleteError = PostNotFoundError | PostPermissionError | PostAlreadyDeletedError
    PostDeleteError
    > => {
    // ビジネスルールに違反するごとに Failure を返す }

    想定外のエラー:throw させる

    想定外のエラーは、インフラやバグに起因するものです。 呼び出し側は通常、報告する以外に何もできません。

    • データベースへの接続失敗
    • ネットワークのタイムアウト
    • メモリ不足
    • undefined のプロパティを読み取るなどのプログラミングミス

    これらのエラーはそのまま throw させ、フレームワークのエラーハンドラーや Sentry のようなエラー監視サービスなど、最上位の一箇所でまとめて処理します。

    // 接続失敗やタイムアウトなどで例外を投げる可能性がある
    const 
    const connectToDatabase: () => Promise<Database>
    connectToDatabase
    = async ():
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <Database> => {
    // ... };
    Tip

    迷ったときは、「呼び出し側はこのエラーを、他のエラーとは異なる方法で処理するだろうか?」 と自問してみてください。 答えが「はい」であれば、それは想定内のエラーであり、Result で表すべきです。

    2 種類のエラーを相互に変換する

    実際には、2 種類のエラーはコードの境界で出会います。

    • throw から Result へ:ユーザー入力に対する JSON.parse のように、ライブラリが想定内の失敗を例外で通知する場合は、Result.fn または Result.try でラップします。
    • Result から throw へ:アプリケーションのエントリーポイントでは、想定しているエラーを処理したうえで、残りは Result.unwrap に throw させます。これにより、エラー監視で検知できるようになります。

    スタックトレースを改善するために想定外のエラーをラップする

    想定外のエラーのスタックトレースは、ライブラリの内部の奥深くを指していて役に立たないことがあります。 そのような場合は、処理を Result.fn でラップし、投げられたエラーを 1 つの UnexpectedError クラスに変換できます。

    まず、エラークラスを定義します。

    Tip

    @praha/error-factory の詳細については、カスタムエラーを参照してください。

    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 UnexpectedError
    UnexpectedError
    extends
    ErrorFactory<"UnexpectedError", "An unexpected error occurred", ErrorFields>(props: {
        name?: "UnexpectedError" | undefined;
        message: "An unexpected error occurred" | ((fields: ErrorFields) => "An unexpected error occurred");
        fields?: ErrorFields | undefined;
    }): (new (options?: ErrorOptions) => Error & Readonly<{
        name: "UnexpectedError";
        message: "An unexpected error occurred";
    }>) & {
        name: "UnexpectedError";
    }

    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?: "UnexpectedError" | undefined
    name
    : 'UnexpectedError',
    message: "An unexpected error occurred" | ((fields: ErrorFields) => "An unexpected error occurred")
    message
    : 'An unexpected error occurred',
    }) {}

    次に、元のエラーを cause として保持しながら処理をラップします。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const findRecord: (id: string) => Result.ResultAsync<string, UnexpectedError>
    findRecord
    =
    import Result
    Result
    .
    function fn<(id: string) => Promise<string>, UnexpectedError>(options: {
        try: (id: string) => Promise<string>;
        catch: (error: unknown) => UnexpectedError;
    }): (id: string) => Result.ResultAsync<string, UnexpectedError> (+3 overloads)

    Wraps a function that may throw and returns a new function that returns 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 new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@example

    Sync try-catch

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

    Sync safe

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

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: async (id: string) => await fetch(`/api/data/${id}`),
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = await fn('abc'); // Result.ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: async () => await Promise.resolve('ok'),
    });
    
    const result = await fn(); // Result.ResultAsync<string, never>
    @categoryCreators
    fn
    ({
    try: (id: string) => Promise<string>
    try
    : (
    id: string
    id
    : string) => {
    // クエリエラーやネットワークエラーなどを投げる可能性がある return
    const performDatabaseOperation: (id: string) => Promise<string>
    performDatabaseOperation
    (
    id: string
    id
    );
    },
    catch: (error: unknown) => UnexpectedError
    catch
    : (
    error: unknown
    error
    ) => new
    constructor UnexpectedError(options?: ErrorOptions): UnexpectedError
    UnexpectedError
    ({
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    }); const
    const result: Result.Result<string, UnexpectedError>
    result
    = await
    const findRecord: (id: string) => Result.ResultAsync<string, UnexpectedError>
    findRecord
    ('123');
    if (
    import Result
    Result
    .
    function isFailure<Result.Result<string, UnexpectedError>>(result: Result.Result<string, UnexpectedError>): result is Result.Failure<UnexpectedError>

    Type guard to check if a Result is a Failure .

    @typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@example
    import { Result } from '@praha/byethrow';
    
    const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
    if (Result.isFailure(result)) {
      console.error(result.error); // Safe access to error
    }
    @categoryType Guards
    isFailure
    (
    const result: Result.Result<string, UnexpectedError>
    result
    )) {
    // スタックトレースは、エラーをラップしたアプリケーション側のコードから始まる
    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
    (
    const result: Result.Failure<UnexpectedError>
    result
    .
    error: UnexpectedError
    error
    .
    Error.stack?: string | undefined
    stack
    );
    // 元のエラーにも引き続きアクセスできる
    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
    (
    const result: Result.Failure<UnexpectedError>
    result
    .
    error: UnexpectedError
    error
    .
    Error.cause?: unknown
    cause
    );
    }

    この方法には次の利点があります。

    1. 読みやすいスタックトレース:新しいエラーはアプリケーション側のコードで作成されるため、そのスタックトレースから、失敗がどこでアプリケーションに入ってきたのかがわかります。
    2. コンテキスト:処理の引数など、デバッグに役立つ情報を付け加えられます。
    3. 情報が失われない:元のエラーには cause プロパティから引き続きアクセスできます。

    アプリケーションのエントリーポイントでは、これらのエラーを unwrap して再び throw し、エラー監視に渡すこともできます。

    まとめ

    目指すのは、すべての throw を Result に置き換えることではなく、それぞれを最も適した場所で使うことです。 Result は明示的な処理が必要な、想定内のビジネスレベルのエラーを扱うのに優れています。一方、インフラレベルで処理すべき想定外のエラーには、引き続き throw が適しています。

    この組み合わせにより、アプリケーション内で起こりうるすべてのエラーをラップする負担を負うことなく、本当に重要な箇所で明示的なエラーハンドリングを実現できます。