Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add isErrorLike() method #68

Merged
merged 12 commits into from
Apr 4, 2022
5 changes: 5 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,8 @@ console.log(error);
```
*/
export function deserializeError(errorObject: ErrorObject | unknown, options?: Options): Error;

/**
Predicate to determine whether an object looks like an error, even if it's not an instance of Error
fregante marked this conversation as resolved.
Show resolved Hide resolved
*/
export function isErrorLike(error: unknown): error is ErrorObject;
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,11 @@ export function deserializeError(value, options = {}) {

return new NonError(value);
}

export function isErrorLike(error) {
return error
&& typeof error === 'object'
&& 'name' in error
&& 'message' in error
&& 'stack' in error;
}
25 changes: 24 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Buffer} from 'node:buffer';
import Stream from 'node:stream';
import test from 'ava';
import {serializeError, deserializeError} from './index.js';
import {serializeError, deserializeError, isErrorLike} from './index.js';

function deserializeNonError(t, value) {
const deserialized = deserializeError(value);
Expand Down Expand Up @@ -383,3 +383,26 @@ test('should serialize properties up to `Options.maxDepth` levels deep', t => {
const levelThree = serializeError(error, {maxDepth: 3});
t.deepEqual(levelThree, {message, name, stack, one: {two: {three: {}}}});
});

test('should identify serialized errors', t => {
t.true(isErrorLike(serializeError(new Error('I’m missing more than just your body'))));
// eslint-disable-next-line unicorn/error-message -- Testing this eventuality
t.true(isErrorLike(serializeError(new Error())));
t.true(isErrorLike({
name: 'Error',
message: 'Is it too late now to say sorry',
stack: 'at <anonymous>:3:14',
}));

t.false(isErrorLike({
name: 'Bluberricious pancakes',
stack: 12,
ingredients: 'Blueberry',
}));

t.false(isErrorLike({
name: 'Edwin Monton',
message: 'We’ve been trying to reach you about your car’s extended warranty',
medium: 'Glass bottle in ocean',
}));
});