#パターンマッチング
複数の異なるエラー型を持つ Result 型を扱う際、異なるエラーシナリオを効果的に処理するためにパターンマッチングは不可欠です。
このガイドでは、複数のエラー型を適切に処理するためのパターンマッチングの使い方を示します。
#なぜユニオンエラーにパターンマッチングが必要なのか?
Result が複数の異なるエラー型で失敗する可能性がある場合、各エラー型を適切に処理する体系的な方法が必要です。
パターンマッチングは、すべての可能なエラーケースを処理するためのクリーンで型安全なアプローチを提供します。
@praha/error-factory の詳細については、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';
import { import Result Result } from '@praha/byethrow';
class class PostNotFoundError PostNotFoundError extends ErrorFactory<"PostNotFoundError", "The requested post was not found.", ErrorFields>(props: {
name: "PostNotFoundError";
message: "The requested post was not found." | ((fields: ErrorFields) => "The requested post was not found.");
fields?: ErrorFields | undefined;
}): (new (options?: ErrorOptions) => Error & Readonly<{
name: "PostNotFoundError";
message: "The requested post was not found.";
}>) & {
name: "PostNotFoundError";
}
ErrorFactory ({
name: "PostNotFoundError" name : 'PostNotFoundError',
message: "The requested post was not found." | ((fields: ErrorFields) => "The requested post was not found.") message : 'The requested post was not found.',
}) {}
class class PostPermissionError PostPermissionError extends ErrorFactory<"PostPermissionError", "You do not have permission to perform this action.", ErrorFields>(props: {
name: "PostPermissionError";
message: "You do not have permission to perform this action." | ((fields: ErrorFields) => "You do not have permission to perform this action.");
fields?: ErrorFields | undefined;
}): (new (options?: ErrorOptions) => Error & Readonly<{
name: "PostPermissionError";
message: "You do not have permission to perform this action.";
}>) & {
name: "PostPermissionError";
}
ErrorFactory ({
name: "PostPermissionError" name : 'PostPermissionError',
message: "You do not have permission to perform this action." | ((fields: ErrorFields) => "You do not have permission to perform this action.") message : 'You do not have permission to perform this action.',
}) {}
class class PostAlreadyDeletedError PostAlreadyDeletedError extends ErrorFactory<"PostAlreadyDeletedError", "This post has already been deleted.", ErrorFields>(props: {
name: "PostAlreadyDeletedError";
message: "This post has already been deleted." | ((fields: ErrorFields) => "This post has already been deleted.");
fields?: ErrorFields | undefined;
}): (new (options?: ErrorOptions) => Error & Readonly<{
name: "PostAlreadyDeletedError";
message: "This post has already been deleted.";
}>) & {
name: "PostAlreadyDeletedError";
}
ErrorFactory ({
name: "PostAlreadyDeletedError" name : 'PostAlreadyDeletedError',
message: "This post has already been deleted." | ((fields: ErrorFields) => "This post has already been deleted.") message : 'This post has already been deleted.',
}) {}
// 投稿削除関数の例
type type PostDeleteError = PostNotFoundError | PostPermissionError | PostAlreadyDeletedError PostDeleteError = (
| class PostNotFoundError PostNotFoundError
| class PostPermissionError PostPermissionError
| class PostAlreadyDeletedError PostAlreadyDeletedError
);
// 複数のエラー型を返す可能性がある関数
const const deletePost: (postId: string) => Result.ResultAsync<void, PostDeleteError> deletePost = async (postId: string postId : string): import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <void, type PostDeleteError = PostNotFoundError | PostPermissionError | PostAlreadyDeletedError PostDeleteError > => {
// いずれかのエラー型を返す可能性のある実装
};
// パターンマッチングによる結果のハンドリング
await import Result Result .const pipe: <Result.ResultAsync<void, PostDeleteError>, Result.ResultAsync<string, PostDeleteError>, Result.ResultAsync<string, PostDeleteError>>(a: Result.ResultAsync<void, PostDeleteError>, ab: (a: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<string, PostDeleteError>, bc: (b: Result.ResultAsync<string, PostDeleteError>) => Result.ResultAsync<string, PostDeleteError>) => Result.ResultAsync<...> (+25 overloads) pipe (
const deletePost: (postId: string) => Result.ResultAsync<void, PostDeleteError> deletePost ('123'),
import Result Result .const map: <Result.ResultAsync<void, PostDeleteError>, string>(fn: (a: void) => string) => (result: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<string, PostDeleteError> (+1 overload) map (() => 'Post deleted successfully!'),
import Result Result .const inspectError: <Result.ResultAsync<string, PostDeleteError>, void>(fn: (a: PostDeleteError) => void) => (result: Result.ResultAsync<string, PostDeleteError>) => Result.ResultAsync<string, PostDeleteError> (+1 overload) inspectError ((error: PostDeleteError error ) => {
// 異なるエラー型を処理するためのパターンマッチング
}),
);#推奨:ts-pattern を使用する
パターンマッチングにはts-patternの使用を強くお勧めします。
優れたTypeScriptサポートを提供し、網羅的なマッチングを保証します。
#インストール
npm install ts-patternyarn add ts-patternpnpm add ts-patternbun add ts-patterndeno add npm:ts-pattern#ts-pattern によるパターンマッチング
import { import Result Result } from '@praha/byethrow';
import { function match<const input, output = typeof unset>(value: input): Match<input, output>match creates a pattern matching expression.
- Use
.with(pattern, handler) to pattern match on the input.
- Use
.exhaustive() or .otherwise(() => defaultValue) to end the expression and get the result.
@exampledeclare let input: "A" | "B";
return match(input)
.with("A", () => "It's an A!")
.with("B", () => "It's a B!")
.exhaustive();
match } from 'ts-pattern';
await import Result Result .const pipe: <Result.ResultAsync<void, PostDeleteError>, Result.ResultAsync<void, PostDeleteError>>(a: Result.ResultAsync<void, PostDeleteError>, ab: (a: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError> (+25 overloads) pipe (
function deletePost(postId: string): Result.ResultAsync<void, PostDeleteError> deletePost ('123'),
import Result Result .const inspectError: <Result.ResultAsync<void, PostDeleteError>, void>(fn: (a: PostDeleteError) => void) => (result: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError> (+1 overload) inspectError ((error: PostDeleteError error ) => {
match<PostDeleteError, typeof unset>(value: PostDeleteError): Match<PostDeleteError, typeof unset>match creates a pattern matching expression.
- Use
.with(pattern, handler) to pattern match on the input.
- Use
.exhaustive() or .otherwise(() => defaultValue) to end the expression and get the result.
@exampledeclare let input: "A" | "B";
return match(input)
.with("A", () => "It's an A!")
.with("B", () => "It's a B!")
.exhaustive();
match (error: PostDeleteError error )
.with<{
readonly name: "PostNotFoundError";
}, void, PostNotFoundError>(pattern: {
readonly name: "PostNotFoundError";
}, handler: (selections: PostNotFoundError, value: PostNotFoundError) => void): Match<PostPermissionError | PostAlreadyDeletedError, typeof unset, [{
readonly name: "PostNotFoundError";
}], void> (+3 overloads)
.with(pattern, handler) Registers a pattern and an handler function that
will be called if the pattern matches the input value.
with ({ name: "PostNotFoundError" name : 'PostNotFoundError' }, () => {
var console: ConsoleThe 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 ('リクエストされた投稿が見つかりませんでした。');
})
.with<{
readonly name: "PostPermissionError";
}, void, PostPermissionError>(pattern: {
readonly name: "PostPermissionError";
}, handler: (selections: PostPermissionError, value: PostPermissionError) => void): Match<PostAlreadyDeletedError, typeof unset, [{
readonly name: "PostNotFoundError";
}, {
readonly name: "PostPermissionError";
}], void> (+3 overloads)
.with(pattern, handler) Registers a pattern and an handler function that
will be called if the pattern matches the input value.
with ({ name: "PostPermissionError" name : 'PostPermissionError' }, () => {
var console: ConsoleThe 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 ('このアクションを実行する権限がありません。');
})
.with<{
readonly name: "PostAlreadyDeletedError";
}, void, PostAlreadyDeletedError>(pattern: {
readonly name: "PostAlreadyDeletedError";
}, handler: (selections: PostAlreadyDeletedError, value: PostAlreadyDeletedError) => void): Match<never, typeof unset, [{
readonly name: "PostNotFoundError";
}, {
readonly name: "PostPermissionError";
}, {
readonly name: "PostAlreadyDeletedError";
}], void> (+3 overloads)
.with(pattern, handler) Registers a pattern and an handler function that
will be called if the pattern matches the input value.
with ({ name: "PostAlreadyDeletedError" name : 'PostAlreadyDeletedError' }, () => {
var console: ConsoleThe 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 ('この投稿は既に削除されています。');
})
.exhaustive: () => void (+1 overload).exhaustive() checks that all cases are handled, and returns the result value.
If you get a NonExhaustiveError, it means that you aren't handling
all cases. You should probably add another .with(...) clause
to match the missing case and prevent runtime errors.
exhaustive (); // すべてのケースが処理されることを保証する
}),
);#代替案:TypeScriptネイティブなパターンマッチング
外部ライブラリを使用したくない場合は、TypeScriptの組み込み機能を使用してパターンマッチングを実装できます。
#instanceof を使用する
import { import Result Result } from '@praha/byethrow';
await import Result Result .const pipe: <Result.ResultAsync<void, PostDeleteError>, Result.ResultAsync<void, PostDeleteError>>(a: Result.ResultAsync<void, PostDeleteError>, ab: (a: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError> (+25 overloads) pipe (
function deletePost(postId: string): Result.ResultAsync<void, PostDeleteError> deletePost ('123'),
import Result Result .const inspectError: <Result.ResultAsync<void, PostDeleteError>, void>(fn: (a: PostDeleteError) => void) => (result: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError> (+1 overload) inspectError ((error: PostDeleteError error ) => {
if (error: PostDeleteError error instanceof class PostNotFoundError PostNotFoundError ) {
var console: ConsoleThe 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 ('リクエストされた投稿が見つかりませんでした。');
}
if (error: PostDeleteError error instanceof class PostPermissionError PostPermissionError ) {
var console: ConsoleThe 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 ('このアクションを実行する権限がありません。');
}
if (error: PostDeleteError error instanceof class PostAlreadyDeletedError PostAlreadyDeletedError ) {
var console: ConsoleThe 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 ('この投稿は既に削除されています。');
}
}),
);#判別可能なユニオンを使用する
import { import Result Result } from '@praha/byethrow';
await import Result Result .const pipe: <Result.ResultAsync<void, PostDeleteError>, Result.ResultAsync<void, PostDeleteError>>(a: Result.ResultAsync<void, PostDeleteError>, ab: (a: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError> (+25 overloads) pipe (
function deletePost(postId: string): Result.ResultAsync<void, PostDeleteError> deletePost ('123'),
import Result Result .const inspectError: <Result.ResultAsync<void, PostDeleteError>, void>(fn: (a: PostDeleteError) => void) => (result: Result.ResultAsync<void, PostDeleteError>) => Result.ResultAsync<void, PostDeleteError> (+1 overload) inspectError ((error: PostDeleteError error ) => {
switch (error: PostDeleteError error .Error.name: "PostNotFoundError" | "PostPermissionError" | "PostAlreadyDeletedError" name ) {
case 'PostNotFoundError':
var console: ConsoleThe 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 ('リクエストされた投稿が見つかりませんでした。');
break;
case 'PostPermissionError':
var console: ConsoleThe 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 ('このアクションを実行する権限がありません。');
break;
case 'PostAlreadyDeletedError':
var console: ConsoleThe 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 ('この投稿は既に削除されています。');
break;
default:
// すべてのエラー型がカバーされていれば、ここには到達しないはず
const const _exhaustiveCheck: never _exhaustiveCheck : never = error: never error ;
throw new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error (`Unhandled error type: ${var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer A function that transforms the results.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found. stringify (const _exhaustiveCheck: never _exhaustiveCheck )}`);
}
}),
);