Error Message Utils
The error-message-utils
package simplifies error management in your web applications and RESTful APIs. It ensures consistent and scalable handling of error messages, saving you time and effort. Moreover, it gives you the ability to assign custom error codes so all possible cases can be handled accordingly.
Getting Started
Install the package:
npm i -S error-message-utils
Examples
Encoding an error:
import { encodeError } from 'error-message-utils';
if (emailExists()) {
throw new Error(encodeError(
'The provided email is already in use.',
'EMAIL_EXISTS'
));
}
Decoding an error:
import { decodeError } from 'error-message-utils';
decodeError('The provided email is already in use.{(EMAIL_EXISTS)}');
Error messages can be extracted recursively from complex structures, including nested cause
data properties from Error
instances:
import { extractMessage } from 'error-message-utils';
extractMessage(new Error('Top level error', {
cause: new Error('First nested cause', {
cause: new Error('Second nested cause'),
}),
}));
extractMessage({
message: {
err: {
message: 'This error message is nested deeply!'
}
}
});
Identifying encoded errors:
import { isEncodedError, encodeError } from 'error-message-utils';
isEncodedError('Some random unencoded error');
isEncodedError(new Error('Some random unencoded error'));
isEncodedError(encodeError('Some unknown error.', 'NASTY_ERROR'));
isEncodedError(encodeError(new Error('Some unknown error.'), 'NASTY_ERROR'));
In some cases, you may want to check whether the extracted error matches the default message provided by this package:
import { isDefaultErrorMessage} from 'error-message-utils';
const DEFAULT_MESSAGE: string = 'The error message could not be extracted, check the logs for more information.';
isDefaultErrorMessage(DEFAULT_MESSAGE);
isDefaultErrorMessage(`${DEFAULT_MESSAGE} and something else...`);
isDefaultErrorMessage(`${DEFAULT_MESSAGE} and something else...`, true);
Types
type IErrorCode = string | number;
type IDecodedError = {
message: string,
code: IErrorCode,
};
Built With
Running the Tests
npm run test:unit
License
MIT