api-error-handler icon indicating copy to clipboard operation
api-error-handler copied to clipboard

Take a callback function?

Open max8hine opened this issue 6 years ago • 2 comments

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.

max8hine avatar Feb 02 '19 06:02 max8hine

@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)
})

blakeembrey avatar Feb 03 '19 04:02 blakeembrey

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

max8hine avatar Feb 03 '19 10:02 max8hine