Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
@icapps/tree-house-errors
Advanced tools
NodeJS default error definitions with an error parser utility function
Custom NodeJS error classes and definitions with an error parser utility function
Install via npm
npm install @icapps/tree-house-errors
or via yarn
yarn add @icapps/tree-house-errors
Base error class which extends from the Error
class.
ApiError
accepts a generic T
for the details
property; if not specified, it defaults to any
.
// All keys are required
const error = {
code: 'BAD_REQUEST_DUE_TO',
message: 'This is a bad request',
}
// All keys are optional
const optionalArgs = {
message: 'Overwrite the message for custom error',
detail: 'Extra details containing pertinent information',
stack: 'stacktrace...',
}
throw new ApiError(400, error, optionalArgs);
Extends from ApiError with a preset of status code 0 and GENERIC_ERROR as error. This should be used when it's internal without needing an actual status code.
throw new GenericError(); // or
throw new GenericError(error, optionalArgs);
Extends from ApiError with a preset of status code 400 and BAD_REQUEST as error.
throw new BadRequestError(); // or
throw new BadRequestError(error, optionalArgs);
Extends from ApiError with a preset of status code 404 and RESOURCE_NOT_FOUND as error.
throw new NotFoundError(); // or
throw new NotFoundError(error, optionalArgs);
Extends from ApiError with a preset of status code 403 and FORBIDDEN as error.
throw new ForbiddenError(); // or
throw new ForbiddenError(error, optionalArgs);
Extends from ApiError with a preset of status code 500 and INTERNAL_ERROR as error.
throw new InternalServerError(); // or
throw new InternalServerError(error, optionalArgs);
Extends from ApiError with a preset of status code 401 and UNAUTHORIZED as error.
throw new UnauthorizedError(); // or
throw new UnauthorizedError(error, optionalArgs);
Extends from ApiError with a preset of status code 400 and INVALID_INPUT as error.
throw new ValidationError(); // or
throw new ValidationError(error, optionalArgs);
Extends from ApiError with a preset of status code 400 and AUTHENTICATION_FAILED as error.
throw new AuthenticationError(); // or
throw new AuthenticationError(error, optionalArgs);
Predefined error types that can be used over multiple projects with a message and code per type. The current list provides following errors:
INTERNAL_ERROR: { code: 'INTERNAL_ERROR',i18n: 'internal_error',message: 'An unkown error occurred' },
INVALID_INPUT: { code: 'INVALID_INPUT', i18n: 'invalid_input', message: 'Invalid input provided' },
AUTHENTICATION_FAILED: { code: 'AUTHENTICATION_FAILED', i18n: 'authentication_failed', message: 'Authentication failed' },
BAD_REQUEST: { code: 'BAD_REQUEST', i18n: 'bad_request', message: 'Bad request' },
MISSING_HEADERS: { code: 'MISSING_HEADERS', i18n: 'missing_headers', message: 'Missing headers' },
UNAUTHORIZED: { code: 'UNAUTHORIZED', i18n: 'unauthorized', message: 'Unauthorized' },
FORBIDDEN: { code: 'FORBIDDEN', i18n: 'forbidden', message: 'No access' },
RESOURCE_NOT_FOUND: { code: 'RESOURCE_NOT_FOUND', i18n: 'resource_not_found', message: 'Resource not found' },
Example
import { errorConfig as errors } from '@icapps/tree-house-errors'
throw new ApiError(400, errors.BAD_REQUEST);
Will return boolean indicating whether error is instance of ApiError
.
Can also be used to provide an extra check matching a specific error type (will only match code, not message)
// Will return true
isApiError(new BadRequestError())
// Will return false
isApiError(new Error('Something'))
// Will return true
isApiError(new BadRequestError(errors.MY_CUSTOM_ERROR), errors.MY_CUSTOM_ERROR)
Will automatically cast to ApiError if succeeds and using Typescript
Will return boolean indicating whether object has all required properties to be a parsed ApiError
.
// Will return true
isJsonApiError({ status: 200, code: 'MY_CODE', title: 'MY_ERROR', detail: {} })
// Will return false
isJsonApiError({ status: 200, code: 'MY_CODE' })
Will automatically cast to ParsedError if succeeds and using Typescript
Parse any data into an error object with all properties needed for jsonade parser. Also parses express-validation
and celebrate
errors.
const error = new BadRequestError(...);
const parsedError = parseErrors(error);
// jsonade serializer afterwards (optional)
serializer.serialize([parsedError]);
With i18n support (optional):
const error = new BadRequestError(...);
const parsedError = parseErrors(error, {
defaultLocale: 'en', // Optional (defaults to 'en')
language: 'nl', // Optional (defaults to 'en')
path: __dirname = '/locales',
});
// jsonade serializer afterwards (optional)
serializer.serialize([parsedError]);
The
parseErrors
function will load the i18n configuration once, and reuse the same instance afterwards. It is not possible to overwrite the configuration after the first call. This has to do with performance and caching of translations.
Parse json object containing errors into javascript ApiError
instances. Will return an array with all non-errors filtered out or default InternalServerError if no errors were found.
try {
await doApiCall(...);
// Returns { errors: [{ status: 400, code: 'BAD_REQUEST', ... }] }
} catch(errorResponse) {
const errors = parseJsonResponse(errorResponse);
// Will return array containing `ApiError` objects
}
Make sure the object contains an
errors
root key:{ errors: [ ... ] }
npm run test
to run all testsnpm run test:coverage
to run all tests with coverage reportWhen you find issues, please report them:
Be sure to include all of the output from the npm command that didn't work as expected. The npm-debug.log file is also helpful to provide.
See the list of contributors who participated in this project.
This project is licensed under the ISC License - see the LICENSE.md file for details
FAQs
NodeJS default error definitions with an error parser utility function
We found that @icapps/tree-house-errors demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 8 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.