Open max8hine opened 5 years ago
@max8hine What is body
in this case? If you're just after logging the error, you can do:
app.use((err, req, res, next) => {
console.log(err)
next(err)
})
body
is what this middleware produce. I found in the index.js
I want to console log the formatted error object, and then some server providers will pick it up and transfer to the provider logs, such as Heroku.
This middleware also runs res.json()
instead of next()
, so it's kind of the end of a req/res. I've been using the middleware at the end of my APIs routes, just like the test.js does.
an example of my use case
const express = require('express')
const createError = require('http-errors')
const errorHandler = require('api-error-handler')
const app = express();
app.get('/', (req, res, next) => {
try {
throw new Error('A ERROR!!!')
} catch (err) {
next(createError(400, Error))
}
})
app.use(errorHandler(
// * just add a callback,
// * that allow us do some background jobs
function(body) {
// body is errorHandler provided
// task 1, console.log error
console.log(body, '🚨')
// Task 2, send a error notification email to admin
...
}
))
Hope the case makes sense here =)
Take a callback function and execute it at the end?
I am having a case that I want to log out the error message in console. It will be easy to passing
body
into a callback function and execute it at the end process.I think it's easy for others who want to do more things with this lib. such as send an error email to the developer, etc.