Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!