logo
byethrow
Guide
Examples
API Reference
Guide
Examples
API Reference
logo
byethrow

Getting Started

Introduction
Why byethrow?
Quick Start
Importing Result

Best Practices

Result vs throw
Custom Error
Pattern Matching

Tools & Integrations

MCP Server
ESLint Plugin

Last Updated: 2025/10/13 08:39:30

Previous PageResult vs throw
Next PagePattern Matching

#Custom Error

When creating errors with Result.fail(), we strongly recommend using custom errors instead of plain strings or generic Error objects. This guide explains what custom errors are, why they're beneficial, and how to create them effectively.

#What are Custom Errors?

Custom errors are specialized error classes that provide more structure and context than generic Error objects. They come in two main forms:

#1. Custom Error Classes (Recommended)

Custom error classes inherit from the built-in Error class and provide additional functionality:

import { 
import Result
Result
} from '@praha/byethrow';
import {
import z
z
} from 'zod';
class
class ValidationError
ValidationError
extends
var Error: ErrorConstructor
Error
{
public override readonly
ValidationError.name: "ValidationError"
name
= 'ValidationError';
constructor(
message: string
message
: string,
options: ErrorOptions | undefined
options
?: ErrorOptions) {
super(
message: string
message
,
options: ErrorOptions | undefined
options
);
} } // Usage with Result.fail() 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.@example
import { 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
.
const 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)
pipe
(
email: string
email
,
import Result
Result
.
const parse: <z.ZodString>(schema: z.ZodString) => (value: unknown) => Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
parse
(
import z
z
.
function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)
string
().
ZodString.email(params?: string | z.core.$ZodCheckEmailParams): z.ZodString
@deprecatedUse z.email() instead.
email
()),
import Result
Result
.
const 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)
mapError
((
error: readonly StandardSchemaV1.Issue[]
error
) => new
constructor ValidationError(message: string, options?: ErrorOptions): ValidationError
ValidationError
('Invalid email format', {
ErrorOptions.cause?: unknown
cause
:
error: readonly StandardSchemaV1.Issue[]
error
})),
); };

#2. Objects with Identifiable Tags

You can also use plain objects with distinguishable properties as error types:

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.@example
import { 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
.
const pipe: <string, Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, Result.Result<string, {
    type: "ValidationError";
    message: string;
    value: string;
}>>(a: string, ab: (a: string) => Result.Result<string, readonly StandardSchemaV1.Issue[]>, bc: (b: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, {
    type: "ValidationError";
    message: string;
    value: string;
}>) => Result.Result<string, {
    type: "ValidationError";
    message: string;
    value: string;
}> (+25 overloads)
pipe
(
email: string
email
,
import Result
Result
.
const parse: <z.ZodString>(schema: z.ZodString) => (value: unknown) => Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
parse
(
import z
z
.
function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)
string
().
ZodString.email(params?: string | z.core.$ZodCheckEmailParams): z.ZodString
@deprecatedUse z.email() instead.
email
()),
import Result
Result
.
const mapError: <Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, {
    type: "ValidationError";
    message: string;
    value: string;
}>(fn: (a: readonly StandardSchemaV1.Issue[]) => {
    type: "ValidationError";
    message: string;
    value: string;
}) => (result: Result.Result<string, readonly StandardSchemaV1.Issue[]>) => Result.Result<string, {
    type: "ValidationError";
    message: string;
    value: string;
}> (+1 overload)
mapError
((
error: readonly StandardSchemaV1.Issue[]
error
) => ({
type: "ValidationError"
type
: 'ValidationError',
message: string
message
: 'Invalid email format',
value: string
value
:
email: string
email
,
})), ); };

#Why Use Custom Error Classes?

While both approaches work, we recommend using custom Error classes for the following reasons:

#Stack Trace Availability

Custom Error classes automatically capture stack traces, making debugging much easier:

import { 
import Result
Result
} from '@praha/byethrow';
class
class DatabaseError
DatabaseError
extends
var Error: ErrorConstructor
Error
{
public override readonly
DatabaseError.name: "DatabaseError"
name
= 'DatabaseError';
constructor(
message: string
message
: string,
options: ErrorOptions | undefined
options
?: ErrorOptions) {
super(
message: string
message
,
options: ErrorOptions | undefined
options
);
} } const
const fetchUser: (id: string) => Result.Result<User, DatabaseError>
fetchUser
= (
id: string
id
: 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.@example
import { 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
<
type User = {
    id: string;
    name: string;
}
User
,
class DatabaseError
DatabaseError
> => {
try { // Database operation... } catch (
function (local var) error: unknown
error
) {
// The stack trace will show exactly where the error occurred return
import Result
Result
.
const fail: <DatabaseError>(error: DatabaseError) => Result.Result<never, DatabaseError> (+1 overload)
fail
(new
constructor DatabaseError(message: string, options?: ErrorOptions): DatabaseError
DatabaseError
('Failed to fetch user'));
} };

#Error Chaining with Cause Option

Custom Error classes support the cause option, allowing you to preserve the original error context:

import { 
import Result
Result
} from '@praha/byethrow';
class
class DatabaseError
DatabaseError
extends
var Error: ErrorConstructor
Error
{
public override readonly
DatabaseError.name: "DatabaseError"
name
= 'DatabaseError';
constructor(
message: string
message
: string,
options: ErrorOptions | undefined
options
?: ErrorOptions) {
super(
message: string
message
,
options: ErrorOptions | undefined
options
);
} } const
const fetchUser: (id: string) => Result.Result<User, DatabaseError>
fetchUser
= (
id: string
id
: 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.@example
import { 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
<
type User = {
    id: string;
    name: string;
}
User
,
class DatabaseError
DatabaseError
> => {
try { // Database operation... } catch (
function (local var) error: unknown
error
) {
// Preserve the original error as cause return
import Result
Result
.
const fail: <DatabaseError>(error: DatabaseError) => Result.Result<never, DatabaseError> (+1 overload)
fail
(new
constructor DatabaseError(message: string, options?: ErrorOptions): DatabaseError
DatabaseError
('Failed to fetch user', {
ErrorOptions.cause?: unknown
cause
:
function (local var) error: unknown
error
})); } };

#Recommended: Using @praha/error-factory

For creating custom error classes efficiently, we recommend using @praha/error-factory. This library reduces boilerplate code and ensures consistent error structures.

#Installation

npm
yarn
pnpm
bun
npm install @praha/error-factory

#Basic Usage with Result

First, define the necessary custom error.

import { 
const ErrorFactory: {
    <Name extends string, Message extends string, Fields extends ErrorFields>(props: {
        name: Name;
        message: Message | ((fields: Fields) => Message);
        fields?: Fields;
    }): ErrorConstructor<Name, Message, Fields>;
    fields<Fields extends ErrorFields>(): Fields;
}
ErrorFactory
} from '@praha/error-factory';
class
class ValidationError
ValidationError
extends
ErrorFactory<"ValidationError", "Invalid input provided", ErrorFields>(props: {
    name: "ValidationError";
    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";
}
ErrorFactory
({
name: "ValidationError"
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";
    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";
}
ErrorFactory
({
name: "QueryError"
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, Message extends string, Fields extends ErrorFields>(props: {
        name: Name;
        message: Message | ((fields: Fields) => Message);
        fields?: Fields;
    }): ErrorConstructor<Name, Message, Fields>;
    fields<Fields extends ErrorFields>(): Fields;
}
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";
    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";
}
ErrorFactory
({
name: "NotFoundError"
name
: 'NotFoundError',
message: "Resource not found" | ((fields: ErrorFields) => "Resource not found")
message
: 'Resource not found',
}) {}

Next, create a function that returns the previously defined custom error together with a Result.

import { 
import Result
Result
} from '@praha/byethrow';
import {
import z
z
} from 'zod';
// Use custom errors in Result operations const
const validateId: (id: string) => Result.Result<string, ValidationError>
validateId
= (
id: string
id
: string) => {
return
import Result
Result
.
const 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)
pipe
(
id: string
id
,
import Result
Result
.
const parse: <z.ZodString>(schema: z.ZodString) => (value: unknown) => Result.Result<string, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
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
.
const 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)
mapError
((
error: readonly StandardSchemaV1.Issue[]
error
) => new
constructor ValidationError(options?: ErrorOptions): ValidationError
ValidationError
({
ErrorOptions.cause?: unknown
cause
:
error: readonly StandardSchemaV1.Issue[]
error
})),
); }; const
const executeQuery: (sql: string) => Result.ResultAsync<QueryResult, QueryError>
executeQuery
= (
sql: string
sql
: string) => {
return
import Result
Result
.
try<() => Promise<QueryResult>, QueryError>(options: {
    immediate: true;
    try: () => Promise<QueryResult>;
    catch: (error: unknown) => QueryError;
}): Result.ResultAsync<QueryResult, QueryError> (+7 overloads)
export try

Wraps a function execution (sync or async) or a Promise in a Result or ResultAsync type, capturing errors and returning them in a structured way.

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.@example

Sync try-catch

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

const fn = Result.try({
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 try-catch with immediate execution

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

const result = Result.try({
immediate: true,
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 fn = Result.try({
safe: true,
try: (x: number) => x + 1,
});

const result = fn(1); // Result.Result<number, never>
@example

Sync safe with immediate execution

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

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

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

Async try-catch

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

const fn = Result.try({
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 try-catch with immediate execution

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

const result = Result.try({
immediate: true,
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 fn = Result.try({
safe: true,
try: async () => await Promise.resolve('ok'),
});

const result = await fn(); // Result.ResultAsync<string, never>
@example

Async safe with immediate execution

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

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

// result is ResultAsync<string, never>
@categoryCreators
try
({
immediate: true
immediate
: true,
try: () => Promise<QueryResult>
try
: () =>
const database: {
    query: (sql: string) => Promise<QueryResult>;
}
database
.
query: (sql: string) => Promise<QueryResult>
query
(
sql: string
sql
),
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
}),
}); }; // Combine everything const
const findUser: (id: string) => Result.ResultAsync<{
    id: string;
    name: string;
}, ValidationError | QueryError | NotFoundError>
findUser
= (
id: string
id
: string) => {
return
import Result
Result
.
const pipe: <Result.Result<string, ValidationError>, Result.ResultAsync<QueryResult, ValidationError | QueryError>, Result.ResultAsync<{
    id: string;
    name: string;
}, ValidationError | QueryError | NotFoundError>>(a: Result.Result<string, ValidationError>, ab: (a: Result.Result<string, ValidationError>) => Result.ResultAsync<QueryResult, ValidationError | QueryError>, bc: (b: Result.ResultAsync<...>) => Result.ResultAsync<...>) => Result.ResultAsync<...> (+25 overloads)
pipe
(
const validateId: (id: string) => Result.Result<string, ValidationError>
validateId
(
id: string
id
),
import Result
Result
.
const andThen: <Result.Result<string, ValidationError>, Result.ResultAsync<QueryResult, QueryError>>(fn: (a: string) => Result.ResultAsync<QueryResult, QueryError>) => (result: Result.Result<string, ValidationError>) => Result.ResultAsync<QueryResult, ValidationError | QueryError> (+1 overload)
andThen
((
id: string
id
) =>
const executeQuery: (sql: string) => Result.ResultAsync<QueryResult, QueryError>
executeQuery
(`SELECT * FROM users WHERE id = '${
id: string
id
}'`)),
import Result
Result
.
const andThen: <Result.ResultAsync<QueryResult, ValidationError | QueryError>, Result.Failure<NotFoundError> | Result.Success<{
    id: string;
    name: string;
}>>(fn: (a: QueryResult) => Result.Failure<NotFoundError> | Result.Success<{
    id: string;
    name: string;
}>) => (result: Result.ResultAsync<QueryResult, ValidationError | QueryError>) => Result.ResultAsync<{
    id: string;
    name: string;
}, ValidationError | ... 1 more ... | NotFoundError> (+1 overload)
andThen
((
row: QueryResult
row
) => {
if (!
row: QueryResult
row
) {
return
import Result
Result
.
const fail: <NotFoundError>(error: NotFoundError) => Result.Result<never, NotFoundError> (+1 overload)
fail
(new
constructor NotFoundError(options?: ErrorOptions): NotFoundError
NotFoundError
());
} return
import Result
Result
.
const succeed: <{
    id: string;
    name: string;
}>(value: {
    id: string;
    name: string;
}) => Result.Result<{
    id: string;
    name: string;
}, never> (+1 overload)
succeed
({
id: string
id
:
row: QueryResult
row
.
string
id
,
name: string
name
:
row: QueryResult
row
.
string
name
});
}), ); };

Finally, execute the function and handle it appropriately.

// Execute and handle errors
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
.
const isSuccess: <{
    id: string;
    name: string;
}>(result: Result.Result<{
    id: string;
    name: string;
}, unknown>) => result is Result.Success<{
    id: string;
    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<{
    id: string;
    name: string;
}, ValidationError | QueryError | NotFoundError>
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<{
    id: string;
    name: string;
}>
result
.
value: {
    id: string;
    name: string;
}
value
);
} else { // Handle each error type separately. 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

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.error(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0 .1.100
error
('Validation error:',
const result: Result.Failure<ValidationError | QueryError | NotFoundError>
result
.
error: ValidationError
error
.
Error.message: "Invalid input provided"
message
);
break; case 'QueryError':
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.error(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0 .1.100
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

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.error(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0 .1.100
error
('Not found error:',
const result: Result.Failure<ValidationError | QueryError | NotFoundError>
result
.
error: NotFoundError
error
.
Error.message: "Resource not found"
message
);
break; } }