#関数をラップする
サードパーティのライブラリ、JSON.parse のような組み込み API、レガシーコードは、例外を投げることがよくあります。
fn と try はそのようなコードをラップし、投げられた例外を Failure に変換します。
#fn で再利用可能なラッパーを作る
fn({ try, catch })ケースを選ぶと、その流れだけを追えますfn は例外を投げる可能性のある関数を受け取り、代わりに Result を返す新しい関数を返します。
import { import Result Result } from '@praha/byethrow';
const const parseJson: (input: string) => Result.Result<unknown, Error> parseJson = import Result Result .function fn<(input: string) => unknown, Error>(options: {
try: (input: string) => unknown;
catch: (error: unknown) => Error;
}): (input: string) => Result.Result<unknown, Error> (+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.@exampleSync 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>
@exampleSync 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>
@exampleAsync 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>
@exampleAsync 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: (input: string) => unknown try : (input: string input : string) => var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse (input: string input ) as unknown,
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Invalid JSON', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const result: Result.Result<unknown, Error> result = const parseJson: (input: string) => Result.Result<unknown, Error> parseJson ('{"name": "Alice"}');
// 型: Result.Result<unknown, Error>受け取るオプションは 2 つです。
try:ラップする関数です。ラップされた関数は同じ引数を受け取ります。catch:投げられた値を独自のエラー型に変換します。投げられた値はunknownなので、causeとして渡して元のエラーを残しておきましょう。
try が正常に値を返すと、その戻り値が Success になります。例外を投げると、catch が返した値が Failure になります。
#非同期関数
try が Promise を返す場合、ラップされた関数は ResultAsync を返します。
reject された Promise も、投げられた例外と同じように Failure に変換されます。
import { import Result Result } from '@praha/byethrow';
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
const const fetchUser: (id: string) => Result.ResultAsync<User, Error> fetchUser = import Result Result .function fn<(id: string) => Promise<User>, Error>(options: {
try: (id: string) => Promise<User>;
catch: (error: unknown) => Error;
}): (id: string) => Result.ResultAsync<User, Error> (+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.@exampleSync 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>
@exampleSync 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>
@exampleAsync 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>
@exampleAsync 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<User> try : async (id: string id : string) => {
const const response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/users/${id: string id }`);
return await const response: Response response .Body.json(): Promise<any> json () as type User = {
id: string;
name: string;
}
User ;
},
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Failed to fetch user', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const result: Result.Result<User, Error> result = await const fetchUser: (id: string) => Result.ResultAsync<User, Error> fetchUser ('u123');
// 型: Result.Result<User, Error>
try は、それ自体が例外を投げるコードをラップするためだけに使いましょう。
HTTP ステータスがエラーを示している場合のような想定内の失敗を伝えるために、自分で throw してはいけません。
代わりに、「Result をつなげる」で紹介しているように、Result.fail を返すステップをつなげてください。
no-throw-in-callback Lint ルールがこの間違いを検出します。
#try でコードを一度だけ実行する
try は関数をすぐに実行し、その結果を Result として返します。
コードをその場で一度だけ実行したい場合に便利です。
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<{
name: string;
}, Error>
result = import Result Result .try<() => {
name: string;
}, Error>(options: {
try: () => {
name: string;
};
catch: (error: unknown) => Error;
}): Result.Result<{
name: string;
}, Error> (+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: () => {
name: string;
}
try : () => var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse ('{"name": "Alice"}') as { name: string name : string },
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Invalid JSON', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
// 型: Result.Result<{ name: string }, Error>オプションは fn と同じですが、try の関数は引数を受け取りません。
非同期関数にも対応しており、その場合は ResultAsync を返します。
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<Response, Error> result = await import Result Result .try<() => Promise<Response>, Error>(options: {
try: () => Promise<Response>;
catch: (error: unknown) => Error;
}): Result.ResultAsync<Response, Error> (+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<Response> try : () => function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch ('/api/health'),
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Health check failed', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
// 型: Result.Result<Response, Error>#fn と try の使い分け
| シナリオ | 使う関数 |
|---|---|
| 引数を受け取ることもある、再利用可能な関数を定義する | fn |
| 必要な場所で、コードを一度だけ実行する | try |
例えば、さまざまな場所から呼び出すユーティリティには fn を、起動時の設定の読み込みのような一度きりの操作には try を使います。
import { import Result Result } from '@praha/byethrow';
// 再利用可能な JSON パーサー
const const parseJson: (input: string) => Result.Result<unknown, ParseError> parseJson = import Result Result .function fn<(input: string) => unknown, ParseError>(options: {
try: (input: string) => unknown;
catch: (error: unknown) => ParseError;
}): (input: string) => Result.Result<unknown, ParseError> (+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.@exampleSync 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>
@exampleSync 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>
@exampleAsync 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>
@exampleAsync 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: (input: string) => unknown try : (input: string input : string) => var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse (input: string input ) as unknown,
catch: (error: unknown) => ParseError catch : (error: unknown error ) => new constructor ParseError(message?: string, options?: ErrorOptions): ParseError (+1 overload) ParseError ('Invalid JSON', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
// 起動時に一度だけ設定を読み込む
const const config: Result.Result<Config, ParseError> config = import Result Result .try<() => Config, ParseError>(options: {
try: () => Config;
catch: (error: unknown) => ParseError;
}): Result.Result<Config, ParseError> (+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: () => Config try : () => var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse (const configText: string configText ) as type Config = {
name: string;
}
Config ,
catch: (error: unknown) => ParseError catch : (error: unknown error ) => new constructor ParseError(message?: string, options?: ErrorOptions): ParseError (+1 overload) ParseError ('Invalid config', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});#例外を投げない関数: safe オプション
関数が例外を投げないことがわかっている場合は、catch の代わりに safe: true を指定します。
エラーの型は never になります。
import { import Result Result } from '@praha/byethrow';
const const double: (x: number) => Result.Result<number, never> double = import Result Result .function fn<(x: number) => number>(options: {
safe: true;
try: (x: number) => number;
}): (x: number) => Result.Result<number, never> (+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.@exampleSync 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>
@exampleSync 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>
@exampleAsync 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>
@exampleAsync 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 ({
safe: true safe : true,
try: (x: number) => number try : (x: number x : number) => x: number x * 2,
});
const const result: Result.Result<number, never> result = const double: (x: number) => Result.Result<number, never> double (5);
// 型: Result.Result<number, never>通常の関数を、Result のパイプラインに組み込める形に変えたいときに便利です。
try も同じオプションを受け付けます。
safe: true を指定すると、例外はキャッチされません。
関数が実際に例外を投げた場合(または Promise が reject された場合)、その例外は通常どおり呼び出し元に伝わります。
関数が失敗しないと確信できる場合にだけ、このオプションを使ってください。
#リファレンス
| API | 用途 |
|---|---|
| fn(options) | 例外を投げる関数を、Result を返す関数にラップする |
| try(options) | 例外を投げる関数を一度だけ実行し、Result を返す |
