0
0
Expressframework~5 mins

Error response formatting in Express

Choose your learning style9 modes available
Introduction
We format error responses to clearly tell the user or developer what went wrong in a simple and consistent way.
When a user sends wrong data to your server.
When a requested resource is not found.
When the server encounters an unexpected problem.
When authentication fails and access is denied.
Syntax
Express
res.status(statusCode).json({ error: 'Error message here' })
Use res.status() to set the HTTP status code for the error.
Use res.json() to send a JSON object with error details.
Examples
Sends a 404 status with a simple error message.
Express
res.status(404).json({ error: 'Page not found' })
Sends a 400 status when user input is wrong.
Express
res.status(400).json({ error: 'Invalid input data' })
Sends a 500 status for unexpected server problems.
Express
res.status(500).json({ error: 'Server error, please try later' })
Sample Program
This Express app checks if the ID is a number and if the item exists. It sends formatted error responses with status codes and JSON error messages.
Express
import express from 'express';
const app = express();
app.use(express.json());

app.get('/item/:id', (req, res) => {
  const id = req.params.id;
  if (isNaN(id)) {
    return res.status(400).json({ error: 'ID must be a number' });
  }
  if (id !== '1') {
    return res.status(404).json({ error: 'Item not found' });
  }
  res.json({ id: 1, name: 'Sample Item' });
});

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: 'Internal server error' });
});

app.listen(3000, () => console.log('Server running on port 3000'));
OutputSuccess
Important Notes
Always set the correct HTTP status code to help clients understand the error type.
Keep error messages clear and simple for easy debugging.
Use a consistent JSON structure for all error responses.
Summary
Format error responses using res.status() and res.json() in Express.
Use clear status codes like 400, 404, and 500 for different errors.
Send simple JSON objects with an error message for easy understanding.