json-api-error-handler v1.0.4
json-api-error-handler
Express error handler that return JSON error description to client.
Installation
Install package with npm
:
npm i json-api-error-handler
Usage
Import jsonAPIErrorHandler
middleware and define as last, after other app.use() and routes calls:
import cookieParser from 'cookie-parser'
import logger from 'morgan'
import jsonAPIErrorHandler from 'json-api-error-handler'
const app = express()
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(jsonAPIErrorHandler) // <- Last middleware
In your routes you can call next()
function, passing anything to argument (except the string 'route'), or throw
an error.
Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware
functions, and call error handling middleware:
app.get('/', function (req, res, next) {
// Some code...
next('This is an error')
// Some code...
})
The error handler send to client a JSON object with fields code, status, description.
{
code: 500,
status: 'Internal Server Error',
description: 'This is an error'
}
If the next()
function argument is an Error
object, in a development enviornment, the description field contains
a stack trace of the error, while in production it contains only the error title.
HTTPError
You can use HTTPError
class to customize JSON response with an HTTP status code:
app.get('/', function (req, res, next) {
// Some code...
next(new HTTPError(404, 'User not found'))
// Some code...
})
{
code: 404,
status: 'Not Found',
description: 'User not found'
}
License
This project is licensed under the MIT license. See the LICENSE file for more info.