You add custom error handling middleware – which is regular middleware but with 4 arguments instead of 3 – to the middleware stack. In this error handler you use res.status(code).send(jsonResponse)
to send the json error.
A simple quick example that will always send status 500 JSON errors:
const bodyParser = require('body-parser')
const express = require('express')
const jsonErrorHandler = (err, req, res, next) => {
res.status(500).send({ error: err });
}
const app = express()
// The other middleware
app.use(bodyParser.json())
// Your handler
app.use(jsonErrorHandler)