Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions apps/web/content/docs/api-reference.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
---
title: API Reference
description: Complete API reference for all exports from @deessejs/errors.
---

This page documents all public exports from @deessejs/errors. Use this as a comprehensive reference for the library's API.

## error()

Creates an error factory function for defining typed, structured errors.

```ts title="title="${f%.mdx}.ts""
const errorFactory = error<T>(config)
```

### Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `config.name` | `string` | Error name identifier (required) |
| `config.message` | `string` | Message template with `{field}` placeholders |
| `config.fields` | `StandardSchemaV1` | Field schema for validation (Zod, Valibot, etc.) |
| `config.inherits` | `ErrorFactory \| ErrorFactory[]` | Parent error(s) to inherit from |

### Returns

An `ErrorFactory` function that creates error instances. The factory has these properties:

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | The error name |
| `inherits` | `ErrorFactory \| ErrorFactory[] \| undefined` | Parent error types |
| `schema` | `StandardSchemaV1 \| undefined` | Field validation schema |
| `rawMessage` | `string \| undefined` | Original message template |

### Example

```ts title="title="${f%.mdx}.ts""
import { error } from '@deessejs/errors';

const ValidationError = error<{ field: string }>({
name: 'ValidationError',
message: 'Field "{field}" is invalid',
inherits: AppError,
});

const err = ValidationError({ field: 'email' });
```

---

## raise()

Throws an error instance. This is the primary mechanism for throwing errors in @deessejs/errors.

```ts title="title="${f%.mdx}.ts""
raise(error: ErrorInstance): never
```

### Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `error` | `ErrorInstance` | The error to throw |

### Returns

`never` — This function always throws.

### Example

```ts title="title="${f%.mdx}.ts""
import { error, raise } from '@deessejs/errors';

const ValidationError = error({ name: 'ValidationError' });

raise(ValidationError({}));
```

---

## is()

Type guard function to check if an error is an instance of a specific error type.

```ts title="title="${f%.mdx}.ts""
const result = is(error, ErrorType)
```

### Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `error` | `unknown` | The error to check |
| `ErrorType` | `ErrorFactory \| ErrorClass` | The error type to check against |

### Returns

`boolean` — `true` if the error matches or inherits from the type.

### Example

```ts title="title="${f%.mdx}.ts""
import { error, is } from '@deessejs/errors';

const AppError = error({ name: 'AppError' });
const ValidationError = error({
name: 'ValidationError',
inherits: AppError,
});

const err = ValidationError({});

is(err, ValidationError); // true
is(err, AppError); // true (through inheritance)
```

---

## causes()

Returns all causes in an error chain.

```ts title="title="${f%.mdx}.ts""
const chain = causes(error: unknown): Error[]
```

### Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `error` | `unknown` | The error to get causes from |

### Returns

`Error[]` — Array of errors in the cause chain, ordered newest to oldest. Returns an empty array for null, undefined, or errors without causes.

### Example

```ts title="title="${f%.mdx}.ts""
import { error, causes } from '@deessejs/errors';

const AppError = error({ name: 'AppError' });
const appErr = AppError({});
appErr.from(new Error('Original error'));

const chain = causes(appErr);
console.log(chain.length); // 1
```

---

## ErrorInstance

The type of object returned by error factories. It extends the native `Error` type.

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Error name identifier |
| `message` | `string` | Human-readable error message |
| `stack` | `string` | Stack trace string |
| `fields` | `T` | User-defined fields |
| `notes` | `string[]` | Additional notes |
| `cause` | `Error \| null` | Direct cause of this error |
| `causes` | `Error[]` | Full cause chain |
| `context` | `Record<string, unknown> \| null` | Injected context data |
| `inherits` | `ErrorFactory \| ErrorFactory[] \| undefined` | Parent error factories |

### Methods

| Method | Description |
|--------|-------------|
| `from(cause: Error)` | Chains a cause error to this error |

---

## See Also

<Cards>
<Card title="Error Factory" href="/docs/error-factory">
Create custom error types.
</Card>
<Card title="Type Checking" href="/docs/type-checking">
Use is() for type guards.
</Card>
<Card title="Exception Chaining" href="/docs/from-method">
Chain errors with from().
</Card>
</Cards>
135 changes: 135 additions & 0 deletions apps/web/content/docs/causes-function.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
---
title: The causes() Function
description: Use the causes() function to traverse error chains and access all causes in an error.
---

The `causes()` function provides a safe way to access the cause chain of any error. It works with both @deessejs/errors instances and native JavaScript errors, returning an empty array for errors without causes.

## Basic Usage

Call `causes()` with an error to get its cause chain as an array:

```ts title="basic.ts"
import { error, causes } from '@deessejs/errors';

const AppError = error({ name: 'AppError' });
const ValidationError = error({ name: 'ValidationError' });

const appErr = AppError({});
appErr.from(ValidationError({ field: 'email' }));
appErr.from(new Error('Network timeout'));

const chain = causes(appErr);

console.log(chain.length); // 2
console.log(chain[0].name); // "ValidationError"
console.log(chain[1].message); // "Network timeout"
```

The returned array contains only the errors that were explicitly added using `from()`, ordered from newest to oldest.

## Why Use causes() Instead of Direct Access?

The `causes()` function handles edge cases that direct property access doesn't:

```ts title="safety.ts"
import { causes } from '@deessejs/errors';

// Works with native errors (no causes property)
const nativeError = new Error('Something failed');
const chain1 = causes(nativeError);
console.log(chain1.length); // 0

// Works with null/undefined (returns empty array)
const chain2 = causes(null);
console.log(chain2.length); // 0

const chain3 = causes(undefined);
console.log(chain3.length); // 0
```

This robustness makes `causes()` ideal for writing generic error handling code that doesn't need to check the error type first.

## Iterating Over the Chain

You can iterate over the causes array to log or process each error in the chain:

```ts title="iterate.ts"
import { error, causes } from '@deessejs/errors';

const AppError = error({ name: 'AppError' });
const ValidationError = error({ name: 'ValidationError' });

const appErr = AppError({});
appErr.from(ValidationError({ field: 'email' }));
appErr.from(new Error('Database connection failed'));

// Log each cause
for (const cause of causes(appErr)) {
console.log(`[${cause.name}] ${cause.message}`);
}

// Output:
// [ValidationError] ValidationError
// [Error] Database connection failed
```

This is useful for building detailed error logs or monitoring dashboards that track where errors originate.

## Building Error Summaries

A common pattern is to build a summary message from the error chain:

```ts title="summary.ts"
import { error, causes } from '@deessejs/errors';

const AppError = error({ name: 'AppError' });
const ValidationError = error({ name: 'ValidationError' });

const appErr = AppError({});
appErr.from(ValidationError({ field: 'email' }));
appErr.from(new Error('DB connection failed'));

const summary = causes(appErr)
.map((cause) => `${cause.name}: ${cause.message}`)
.join(' → ');

console.log(summary);
// "ValidationError: ValidationError → Error: DB connection failed"
```

## Combining with is()

Use `causes()` with `is()` to search for specific error types in the chain:

```ts title="combined.ts"
import { error, causes, is } from '@deessejs/errors';

const AppError = error({ name: 'AppError' });
const NetworkError = error({ name: 'NetworkError' });
const ValidationError = error({ name: 'ValidationError' });

const appErr = AppError({});
appErr.from(NetworkError({ endpoint: '/api/users' }));
appErr.from(ValidationError({ field: 'email' }));

// Check if any cause is a NetworkError
const hasNetworkFailure = causes(appErr).some(
(cause) => is(cause, NetworkError)
);

console.log(hasNetworkFailure); // true
```

This pattern is useful when you need to know not just that an error happened, but what kind of errors were involved in its chain.

## See Also

<Cards>
<Card title="Exception Chaining" href="/docs/from-method">
Learn how to build error chains with from().
</Card>
<Card title="Type Checking" href="/docs/type-checking">
Use is() to check error types.
</Card>
</Cards>
Loading
Loading