@salma-dev/error-handler
v1.0.12
Published
error handling package
Downloads
4
Readme
Error handler middleware
the error handler can be used to handle different http errors
to install:
npm i @salma-dev/error-handler
to integerate it with your express:
commonjs:
const { RestApiErrorHandler } = require('@salma-dev/error-handler')
const app = require('express')()
..
//app config
..
app.use(RestApiErrorHandler)
the handler will catch any error that is thrown inside your app routes
you can import different errors to throw in your app:
| Error | Description | Status code | | :--- | :----: | ---: | | NotFoundError |used to handle not found resource | 404 | | BadRequest | used to handle invalid data | 400 | | NotAuthorizedError | to deny authorization on some resource | 401 | | ForbiddenError |when the user is authenticated but has no permission to use the resource | 403 | | ConflictError | sometimes used to prevent data duplication | 409 | | RequestValidationError | this is useful is if you use express-validator, it takes the errors array and returns another with status | 400 |
you can import any of these errors and throw in your route handler like this:
const {NotFoundError} = require('@salma-dev/error-handler')
...
//some code
..
app.get('/resource/:id', function(req, res){
//some code
throw new NotFoundError()
})
this will cause the handler to return response with body like this:
{
"errors": [{"message": "Not Found"}]
}