関数をラップする

例外を投げるコード(サードパーティライブラリ、組み込み API、レガシーコード)を扱う必要がある場合があります。 fntry 関数は、これらの例外を投げる可能性のある操作をラップし、Result 型に変換します。

fnで再利用可能な関数を作成する

fn 関数は、エラーを投げる可能性のある関数をラップし、Result 返す新しい関数を返します。 再利用可能な関数を作成したい場合に便利です。

import { 
import Result
Result
} from '@praha/byethrow';
const
const parseJSON: (input: string) => Result.Result<unknown, Error>
parseJSON
=
import Result
Result
.
fn<(input: string) => unknown, Error>(options: {
    try: (input: string) => unknown;
    catch: (error: unknown) => Error;
}): (input: string) => Result.Result<unknown, Error> (+3 overloads)
export fn

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.

@function@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: (input: string) => unknown
try
: (
input: string
input
: string) =>
var JSON: JSON

An 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): any

Converts 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> if (
import Result
Result
.
const isSuccess: <unknown>(result: Result.Result<unknown, unknown>) => result is Result.Success<unknown>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<unknown, Error>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<unknown>
result
.
value: unknown
value
); // { name: "Alice" }
}

動作の仕組み

  • try プロパティには、エラーを投げる可能性のある関数を含めます(引数を受け取れます)
  • catch プロパティは、投げられらたエラーを処理し、任意のエラー型に変換します
  • エラーを投げる代わりに Result を返すラップされた関数を返します

エラーを投げない関数

関数がエラーを投げない事が確実な場合は、safe オプションを使用します。

import { 
import Result
Result
} from '@praha/byethrow';
const
const double: (x: number) => Result.Result<number, never>
double
=
import Result
Result
.
fn<(x: number) => number>(options: {
    safe: true;
    try: (x: number) => number;
}): (x: number) => Result.Result<number, never> (+3 overloads)
export fn

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.

@function@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
({
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> // エラー型は `never` です。例外が発生しないことを保証しているためです

非同期関数での使用

fn 関数は非同期関数をシームレスに処理し、ResultAsync を生成する関数を返します。

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

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.

@function@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<{
    id: string;
    name: string;
}>
try
: async (
id: string
id
: string) => {
const
const response: Response
response
= await
function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)
fetch
(`/api/users/${
id: string
id
}`);
if (!
const response: Response
response
.
Response.ok: boolean

The ok read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.

MDN Reference

ok
) throw new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Not found');
return await
const response: Response
response
.
Body.json(): Promise<any>
json
() as {
id: string
id
: string;
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
('Failed to fetch user', {
ErrorOptions.cause?: unknown
cause
:
error: unknown
error
}),
}); const
const result: Result.Result<{
    id: string;
    name: string;
}, Error>
result
= await
const fetchUser: (id: string) => Result.ResultAsync<{
    id: string;
    name: string;
}, Error>
fetchUser
('123');
// 型: Result.Result<{ id: string; name: string }, Error>

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.

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

Sync try-catch

import { Result } from '@praha/byethrow';

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

// result is Result<number, Error>
@example

Sync safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

import { Result } from '@praha/byethrow';

const result = Result.try({
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
try: () => {
    name: string;
}
try
: () =>
var JSON: JSON

An 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): any

Converts 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> if (
import Result
Result
.
const isSuccess: <{
    name: string;
}>(result: Result.Result<{
    name: string;
}, unknown>) => result is Result.Success<{
    name: string;
}>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<{
    name: string;
}, Error>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<{
    name: string;
}>
result
.
value: {
    name: string;
}
value
.
name: string
name
); // "Alice"
}

動作の仕組み

  • try プロパティには、エラーを投げる可能性のある引数なしの関数を含めます
  • catch プロパティは、投げられたエラーを処理し、任意のエラー型に変換します
  • 関数は即座に実行され、Result を返します

エラーを投げない関数

関数がエラーを投げない事が確実な場合は、safe オプションを使用します。

import { 
import Result
Result
} from '@praha/byethrow';
const
const result: Result.Result<number, never>
result
=
import Result
Result
.
try<() => number>(options: {
    safe: true;
    try: () => number;
}): Result.Result<number, never> (+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.

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

Sync try-catch

import { Result } from '@praha/byethrow';

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

// result is Result<number, Error>
@example

Sync safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

import { Result } from '@praha/byethrow';

const result = Result.try({
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
safe: true
safe
: true,
try: () => number
try
: () =>
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() + 1,
}); // 型: Result.Result<number, never> // エラー型は `never` です。例外が発生しないことを保証しているためです

非同期関数での使用

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.

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

Sync try-catch

import { Result } from '@praha/byethrow';

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

// result is Result<number, Error>
@example

Sync safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

import { Result } from '@praha/byethrow';

const result = Result.try({
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
try: () => Promise<Response>
try
: () =>
function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)
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>

fntry 関数の使い分け

シナリオ使用する関数
一度実行してすぐに結果を取得するtry
再利用可能なラップされた関数を作成するfn
関数が引数を受け取る必要があるfn
インラインの一回限りのエラーハンドリングtry

例:それぞれを使うべき場面

一回限りの実行には try を使用します。

import { 
import Result
Result
} from '@praha/byethrow';
// 起動時に一度だけ設定を読み込む const
const config: Result.Result<Config, ConfigError>
config
=
import Result
Result
.
try<() => Config, ConfigError>(options: {
    try: () => Config;
    catch: (error: unknown) => ConfigError;
}): Result.Result<Config, ConfigError> (+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.

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

Sync try-catch

import { Result } from '@praha/byethrow';

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

// result is Result<number, Error>
@example

Sync safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

import { Result } from '@praha/byethrow';

const result = Result.try({
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
try: () => Config
try
: () =>
var JSON: JSON

An 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): any

Converts 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
type Config = {
    name: string;
}
Config
,
catch: (error: unknown) => ConfigError
catch
: (
error: unknown
error
) => new
constructor ConfigError(message?: string, options?: ErrorOptions): ConfigError (+1 overload)
ConfigError
('Invalid config', {
ErrorOptions.cause?: unknown
cause
:
error: unknown
error
}),
});

再利用可能なユーティリティには fn を使用します。

import { 
import Result
Result
} from '@praha/byethrow';
// 再利用可能な JSON パーサーを作成 const
const parseJSON: (input: string) => Result.Result<unknown, ParseError>
parseJSON
=
import Result
Result
.
fn<(input: string) => unknown, ParseError>(options: {
    try: (input: string) => unknown;
    catch: (error: unknown) => ParseError;
}): (input: string) => Result.Result<unknown, ParseError> (+3 overloads)
export fn

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.

@function@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: (input: string) => unknown
try
: (
input: string
input
: string) =>
var JSON: JSON

An 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): any

Converts 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<unknown, ParseError>
config
=
const parseJSON: (input: string) => Result.Result<unknown, ParseError>
parseJSON
('{"name": "Alice"}');
const
const data: Result.Result<unknown, ParseError>
data
=
const parseJSON: (input: string) => Result.Result<unknown, ParseError>
parseJSON
('{"name": "Bob"}');

リファレンス

関数目的
try(options)エラーを投げる関数を実行し Result を返す
fn(options)エラーを投げる関数を Result を返す関数にラップする