Skip to content

Commit

Permalink
Make it work better in the browser (#27)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
vladimiry and sindresorhus authored Mar 11, 2020
1 parent 480ed36 commit 728be12
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 15 deletions.
16 changes: 13 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
'use strict';
const {inspect} = require('util');

class NonError extends Error {
constructor(message) {
super(inspect(message));
super(NonError._prepareSuperMessage(message));
this.name = 'NonError';
Error.captureStackTrace(this, NonError);

if (Error.captureStackTrace) {
Error.captureStackTrace(this, NonError);
}
}

static _prepareSuperMessage(message) {
try {
return JSON.stringify(message);
} catch (_) {
return String(message);
}
}
}

Expand Down
33 changes: 21 additions & 12 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import test from 'ava';
import {serializeError, deserializeError} from '.';

function deserializeNonError(t, value) {
const deserialized = deserializeError(value);
t.true(deserialized instanceof Error);
t.is(deserialized.constructor.name, 'NonError');
t.is(deserialized.message, JSON.stringify(value));
}

test('main', t => {
const serialized = serializeError(new Error('foo'));
const keys = Object.keys(serialized);
Expand Down Expand Up @@ -115,27 +122,29 @@ test('should handle top-level null values', t => {
});

test('should deserialize null', t => {
const deserialized = deserializeError(null);
t.true(deserialized instanceof Error);
t.is(deserialized.message, 'null');
deserializeNonError(t, null);
});

test('should deserialize number', t => {
const deserialized = deserializeError(1);
t.true(deserialized instanceof Error);
t.is(deserialized.message, '1');
deserializeNonError(t, 1);
});

test('should deserialize error', t => {
const deserialized = deserializeError(new Error('test'));
t.true(deserialized instanceof Error);
t.is(deserialized.message, 'test');
test('should deserialize boolean', t => {
deserializeNonError(t, true);
});

test('should deserialize string', t => {
deserializeNonError(t, '123');
});

test('should deserialize array', t => {
const deserialized = deserializeError([1]);
deserializeNonError(t, [1]);
});

test('should deserialize error', t => {
const deserialized = deserializeError(new Error('test'));
t.true(deserialized instanceof Error);
t.is(deserialized.message, '[ 1 ]');
t.is(deserialized.message, 'test');
});

test('should deserialize and preserve existing properties', t => {
Expand Down

0 comments on commit 728be12

Please sign in to comment.