Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
How can I get this custom middleware to run when an error occurs in express?

Hello totally awesome cool beautiful people! I am trying to get this custom middleware function to run upon an error. I am using express and I have a custom middleware function which should run when a new error is thrown.

All of this is written in express. I have read the docs and am still struggling to get this correct. Here is the middleware function.

const errorHandler = (err, req, res, next) => {
    console.log("running error handler middleware")
    const statusCode = res.statusCode ? res.statusCode : 500
    res.status(statusCode)
    res.json({
        message: err.message,
        stack: process.env.NODE_ENV === "production" ? null : err.stack
    })
}


module.exports = errorHandler

Here is my entry point

const express = require('express')
const dotenv = require('dotenv').config()
const colors = require('colors')
const errorHandler = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const port = process.env.PORT || 5000
const app = express()

connectDB()


//these lines of middleware allow us to grab info from the req.body
app.use(express.json())
app.use(express.urlencoded({extended:false}))

app.use('/api/goals', require('./routes/goalRoutes'))
app.use('/api/users', require('./routes/userRoutes'))

//pulling in our error handler middleware
app.use(errorHandler)

app.listen(port, () => {
    console.log(`Server started on port ${port}`)
})

I have confirmed my file structure is correct and I am pulling the middleware in from the correct location. I have also made sure to place my app.use(errorHandler) at the bottom of my code to ensure it is the last error handler to run.

As of now when I encounter an error, my application crashed completely and does not return a json response with a stack trace.

This is going to cause issues later when trying to send errors back to the client side.

I can always go back to manually defining them through res.status(statusCode).json({message}) but this is the "node" way of doing things and does not implement the express syntax of "throw new Error(message)"

Any ideas on how to get a json response out of this without the app crashing while still using custom error handling and express throw new Error?

Thank you so much for the time, I appreciate it!

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda