expressjs / api-error-handler

Express error handlers for JSON APIs
MIT License
101 stars 23 forks source link

Take a callback function? #10

Open max8hine opened 5 years ago

max8hine commented 5 years ago

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.

api.use(errorHandler(body => { console.log(body }))

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.

blakeembrey commented 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)
})
max8hine commented 5 years ago

Please correct me if my case is a wrong use case.

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 =)