#カスタムエラー
Result のエラーにはどんな値でも使えますが、単なる文字列や汎用的な Error オブジェクトでは、呼び出し側が失敗の種類を区別しにくくなります。
失敗の種類ごとに専用のエラー型を用意することを強く推奨します。
このページでは、その選択肢と、カスタムエラーを効率よく作成する方法を説明します。
#カスタムエラーを定義する 2 つの方法
#1. エラークラス(推奨)
組み込みの Error クラスを継承したクラスを定義し、一意な 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.@exampleimport { 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.@exampleimport { 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.@exampleBasic 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>>
@exampleCurried 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.@exampleFailure 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') }
@exampleSuccess 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. タグ付きオブジェクト
エラーの種類を識別するプロパティを持つプレーンオブジェクトを使うこともできます。
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.@exampleimport { 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.@exampleimport { 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.@exampleBasic 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>>
@exampleCurried 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.@exampleFailure 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') }
@exampleSuccess 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 ,
})),
);
};#エラークラスを推奨する理由
どちらの方法でも呼び出し側はエラーを区別できますが、エラークラスには実用上の利点がいくつかあります。
#スタックトレースとエラーチェーン
Error は作成された場所を示すスタックトレースを記録し、cause オプションはその原因となった元のエラーを保持します。
この 2 つを組み合わせることで、デバッグがずっと簡単になります。
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.@exampleSync 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>
@exampleSync safe
import { Result } from '@praha/byethrow';
const result = Result.try({
safe: true,
try: () => Math.random() + 1,
});
// result is Result<number, never>
@exampleAsync 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>
@exampleAsync 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 ),
// スタックトレースはここを指し、元のエラーは `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 }),
});#throw との互換性
Result のエラーは、アプリケーションの境界で unwrap を使ったときなど、最終的に throw されることがあります。
エラー監視ツールやランタイムは、throw される値が Error のインスタンスであることを前提としています。プレーンオブジェクトを throw するとスタックトレースがなく、うまく報告されないことがよくあります。
#推奨:@praha/error-factory を使う
エラークラスを手書きしていると、すぐに同じようなコードの繰り返しになります。
@praha/error-factory を使うと、定型的なコードを減らし、エラーの構造を一貫させることができます。
#インストール
npm install @praha/error-factoryyarn add @praha/error-factorypnpm add @praha/error-factorybun add @praha/error-factorydeno add npm:@praha/error-factory#エラーを定義する
ErrorFactory が返すクラスを継承します。
name はリテラル型になるため、TypeScript はエラーのユニオン型を 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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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',
// エラーが持つ追加のフィールド
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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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 には、フィールドからメッセージを組み立てる関数を指定することもできます。
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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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.@exampleBasic 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"
@exampleOmitting name
class NotFoundError extends ErrorFactory({
message: 'Resource not found',
}) {}
const error = new NotFoundError();
console.error(error.name); // "NotFoundError" (resolved from new.target.name)
@exampleWith 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
@exampleWith 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"
@exampleDynamic 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 }>(),
}) {}#Result の中でエラーを使う
失敗が発生した場所でエラーを作成し、元のエラーを cause として渡したうえで、必要なフィールドを埋めます。
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.@exampleimport { 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.@exampleBasic 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>>
@exampleCurried 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.@exampleFailure 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') }
@exampleSuccess 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.@exampleSync 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>
@exampleSync safe
import { Result } from '@praha/byethrow';
const result = Result.try({
safe: true,
try: () => Math.random() + 1,
});
// result is Result<number, never>
@exampleAsync 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>
@exampleAsync 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.@exampleimport { 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.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure 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' }
@exampleFailure 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.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure 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' }
@exampleFailure 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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 });
}),
);
};
// 型: (id: string) => Result.ResultAsync<{ id: string; name: string }, ValidationError | QueryError | NotFoundError>#エラーを処理する
各エラーはリテラル型の name を持つため、switch 文によってエラーをフィールドも含めた正確なクラスに絞り込めます。
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.@exampleimport { 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[]): voidThe console.log() static method outputs a message to the console.
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[]): voidThe 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.
error ('Validation error:', const result: Result.Failure<ValidationError | QueryError | NotFoundError> result .error: ValidationError error .Error.message: "Invalid input provided" message );
break;
case 'QueryError':
// QueryError に絞り込まれているので `query` にアクセスできる
var console: Console console .Console.error(...data: any[]): voidThe 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.
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[]): voidThe 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.
error ('Not found error:', const result: Result.Failure<ValidationError | QueryError | NotFoundError> result .error: NotFoundError error .Error.message: "Resource not found" message );
break;
}
}網羅性チェックを含む、エラーのユニオン型を処理するその他の方法については、パターンマッチングを参照してください。
