This package provides a decorator to use with Typescript to easily manage error (handled as unhandled). It also allow customisation for response status code and/or body response content. Warning, this package is meant for Hapi only !
To install this package, you need only one thing : NodeJS > 10.15.
You can use it for Typescript only.
To install, just run this command :
npm install --save sfs-error-hapi@latest
|^20.0||2.0.0||That's on this page|
How to use
You just need to decorate one of your handler like below to handle error without any customization :
Then, use it inside one of your route like below :
If your source code throw any error, then it'll be caught and sent response will look like this :
You can also create your own error class and customize its content. The BaseError class provides a single method .toString() that is used to send HTTP response body. You can customize it as you wish but this method is required. You can add as many attributes as you wish.
If your method does throw an instance of CustomError, then the resulting HTTP status code will be 501 and the output body will look like below :
Multiple error types
Of course, you can manage like above as many error types as you wish :
You may want to log error somehow. Added with v1.1.0 only, you can also provide a logger to the
ErrorHandler with a method
.error(message: any): void which will log the caught error.
For example, imagine you have your own logger class :
Running the tests
I used Mocha and Chai to test this package. You can also get coverage thanks to NYC package (these are only used for development purposes).
This package has been tested mainly with integrations tests because its hard dependent to Hapi.
You can test package by running the following command :
And you can also get code coverage with the following command :
npm run coverage
- Prettierc - An excellent source code formatter
- Mocha - Famous unit test runner
- Chai - Fantastic assertion library
- SinonJS - Amazing mock library
We use GitLab for versioning.
- Sébastien FRANCOIS - Initial work - @francois.sebastien.emile
This project is licensed under the MIT License.