Skip to content

Commit

Permalink
Improve usage examples
Browse files Browse the repository at this point in the history
Closes #45
  • Loading branch information
sindresorhus committed Apr 29, 2021
1 parent 5a318e5 commit d853349
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 14 deletions.
13 changes: 13 additions & 0 deletions index.d.ts
Expand Up @@ -51,17 +51,28 @@ console.log(error);
console.log(serializeError(error));
//=> {name: 'Error', message: '🦄', stack: 'Error: 🦄\n at Object.<anonymous> …'}
```
@example
```
import {serializeError} from 'serialize-error';
class ErrorWithDate extends Error {
constructor() {
super();
this.date = new Date();
}
}
const error = new ErrorWithDate();
console.log(serializeError(error));
//=> {date: '1970-01-01T00:00:00.000Z', name, message, stack}
```
@example
```
import {serializeError} from 'serialize-error';
class ErrorWithToJSON extends Error {
constructor() {
Expand All @@ -73,7 +84,9 @@ class ErrorWithToJSON extends Error {
return serializeError(this);
}
}
const error = new ErrorWithToJSON();
console.log(serializeError(error));
// => {date: '1970-01-01T00:00:00.000Z', message: '🦄', name, stack}
```
Expand Down
38 changes: 24 additions & 14 deletions readme.md
Expand Up @@ -48,30 +48,40 @@ Circular references are handled.
If the input object has a `.toJSON()` method, then it's called instead of serializing the object's properties.
It's up to `.toJSON()` implementation to handle circular references and enumerability of the properties.

`.toJSON` example:
`.toJSON` examples:

```js
const {serializeError} = require('serialize-error');

class ErrorWithDate extends Error {
constructor() {
super();
this.date = new Date();
}
constructor() {
super();
this.date = new Date();
}
}

const error = new ErrorWithDate();
serializeError(date);

serializeError(error);
// => {date: '1970-01-01T00:00:00.000Z', name, message, stack}
```

```js
const {serializeError} = require('serialize-error');

class ErrorWithToJSON extends Error {
constructor() {
super('🦄');
this.date = new Date();
}

toJSON() {
return serializeError(this);
}
constructor() {
super('🦄');
this.date = new Date();
}

toJSON() {
return serializeError(this);
}
}

const error = new ErrorWithToJSON();

console.log(serializeError(error));
// => {date: '1970-01-01T00:00:00.000Z', message: '🦄', name, stack}
```
Expand Down

0 comments on commit d853349

Please sign in to comment.