Advanced Error
Node Js Error Extended class with advanced features
Install
$ npm i --save @da-fat-company/advanced-error
AdvancedError
Throw using object
'use strict';
const HTTPStatus = require('http-status');
const AdvancedError = require('@da-fat-company/advanced-error');
throw new AdvancedError({
title: 'Error title',
message: 'Error description',
status: HTTPStatus.BAD_REQUEST,
privacy: AdvancedError.IS_PUBLIC,
metadata: {
foo: 'bar'
}
});
Throw from standard Error
'use strict';
const HTTPStatus = require('http-status');
const AdvancedError = require('@da-fat-company/advanced-error');
const error = new Error('Uncaught exception');
throw AdvancedError.createFromError(error);
Throw from standard Error adding custom attributes as object
'use strict';
const HTTPStatus = require('http-status');
const AdvancedError = require('@da-fat-company/advanced-error');
const error = new Error('Uncaught exception');
const attributes = {
title: 'Error title',
status: HTTPStatus.BAD_REQUEST,
privacy: AdvancedError.IS_PRIVATE,
metadata: {
foo: 'bar'
}
}
throw AdvancedError.createFromError(error, attributes);
Throw from standard Error adding custom attributes as arguments (legacy style)
'use strict';
const HTTPStatus = require('http-status');
const AdvancedError = require('@da-fat-company/advanced-error');
const error = new Error('Uncaught exception');
const attributes = {
title: 'Error title',
status: HTTPStatus.BAD_REQUEST,
privacy: AdvancedError.IS_PUBLIC,
metadata: {
foo: 'bar'
}
}
throw AdvancedError.createFromError(
error,
'Error title',
HTTPStatus.BAD_REQUEST, // Status code
AdvancedError.IS_PUBLIC, // Privacy
{foo: 'bar'} // Some metadata
);
Add Middlewares
Middlewares are functions called at the end of AdvancedError constructor. When you add a middleware it is available globaly for all your AdvancedError usage (only if you add middleware first).
'use strict';
const HTTPStatus = require('http-status');
const AdvancedError = require('@da-fat-company/advanced-error');
AdvancedError.use(() => {
console.log('This log will be shown for each thrown AdvancedError');
});
AdvancedError.use((error) => {
console.log('The current AdvancedError object is passed as first argument', error);
});
AdvancedError.use((error) => {
if (error.privacy === AdvancedError.IS_PUBLIC) {
console.log('Do something is the error is public');
} else {
console.log('Do something is the error is private');
}
});
throw new AdvancedError({
title: 'Error title',
message: 'Error description',
status: HTTPStatus.BAD_REQUEST,
privacy: AdvancedError.IS_PUBLIC,
metadata: {
foo: 'bar'
}
});
Remove Middlewares
'use strict';
const HTTPStatus = require('http-status');
const AdvancedError = require('@da-fat-company/advanced-error');
AdvancedError.resetMiddlewares(); // This will remove all existing middleware
throw new AdvancedError({
title: 'Error title',
message: 'Error description',
status: HTTPStatus.BAD_REQUEST,
privacy: AdvancedError.IS_PUBLIC,
metadata: {
foo: 'bar'
}
});