0
0
Expressframework~5 mins

Why error handling is critical in Express

Choose your learning style9 modes available
Introduction

Error handling helps your app stay strong and friendly when things go wrong. It stops crashes and shows helpful messages instead of confusing errors.

When a user sends wrong data to your server
When a database connection fails
When a requested page or resource is missing
When an unexpected bug happens in your code
When you want to log errors for fixing later
Syntax
Express
app.use((err, req, res, next) => {
  res.status(500).send('Something broke!')
})
This is an Express error-handling middleware function with four parameters.
It catches errors passed with next(err) or thrown in routes.
Examples
Logs the error stack to the console and sends a 500 status with a message.
Express
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Internal Server Error')
})
Passes a 404 error to the error handler if user is missing.
Express
app.get('/user/:id', (req, res, next) => {
  const user = getUser(req.params.id)
  if (!user) {
    const err = new Error('User not found')
    err.status = 404
    return next(err)
  }
  res.send(user)
})
Sample Program

This simple Express app throws an error on the home page route. The error handler catches it, logs the message, and sends a friendly response.

Express
import express from 'express'
const app = express()

app.get('/', (req, res) => {
  throw new Error('Oops!')
})

app.use((err, req, res, next) => {
  console.error('Error caught:', err.message)
  res.status(500).send('Something went wrong!')
})

app.listen(3000, () => console.log('Server running on http://localhost:3000'))
OutputSuccess
Important Notes

Always place error-handling middleware after all other app routes and middleware.

Use error handling to keep your app from crashing and to give users clear feedback.

Summary

Error handling keeps your app stable and user-friendly.

It catches problems early and prevents crashes.

Express uses special middleware with four parameters for error handling.