#Wrapping Functions
Third-party libraries, built-in APIs such as JSON.parse, and legacy code often throw exceptions.
fn and try wrap such code and convert thrown exceptions into Failure results.
#Creating Reusable Wrappers with fn
fn({ try, catch })Select a case to follow its pathfn takes a potentially throwing function and returns a new function that returns a Result instead:
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"}');
// Type: Result.Result<unknown, Error>It takes two options:
try: The function to wrap. The wrapped function accepts the same arguments.catch: Converts the thrown value into your error type. The thrown value isunknown, so pass it ascauseto keep the original error.
If try returns normally, its return value becomes a Success. If it throws, the value returned by catch becomes a Failure.
#Async Functions
If try returns a Promise, the wrapped function returns a ResultAsync.
A rejected promise is converted into a Failure in the same way as a thrown exception:
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');
// Type: Result.Result<User, Error>
Use try only to wrap code that throws on its own.
Don't throw inside it yourself to signal an expected failure, such as a non-OK HTTP status.
Instead, chain a step that returns Result.fail, as shown in Chaining Results.
The no-throw-in-callback lint rule detects this mistake.
#Running Code Once with try
try runs a function immediately and returns its outcome as a Result.
It is convenient when you only need to run the code once, in place:
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 }),
});
// Type: Result.Result<{ name: string }, Error>The options are the same as for fn, except that the try function takes no arguments.
Async functions are supported as well, and return a 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 }),
});
// Type: Result.Result<Response, Error>#Choosing Between fn and try
| Scenario | Function to use |
|---|---|
| Define a reusable function, possibly with arguments | fn |
| Run the code once, right where you need it | try |
For example, use fn for a utility called from many places, and try for a one-off operation such as reading configuration at startup:
import { import Result Result } from '@praha/byethrow';
// A reusable JSON parser
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 }),
});
// Reading the configuration once at startup
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 }),
});#Functions That Never Throw: the safe Option
If a function is known not to throw, pass safe: true instead of catch.
The error type becomes 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);
// Type: Result.Result<number, never>This is useful for turning a plain function into one that fits into a Result pipeline.
try accepts the same option.
With safe: true, exceptions are not caught.
If the function does throw (or its promise rejects), the exception propagates to the caller as usual.
Only use this option when you are sure the function cannot fail.
#References
| API | Purpose |
|---|---|
| fn(options) | Wrap a throwing function into a function returning Result |
| try(options) | Run a throwing function once and return a Result |
