0
0
ExpressHow-ToBeginner · 3 min read

How to Return Error Response in Express: Simple Guide

In Express, return an error response by setting the HTTP status code with res.status(code) and sending a message using res.json() or res.send(). For example, res.status(404).json({ error: 'Not found' }) sends a 404 error with a JSON message.
📐

Syntax

Use res.status(code) to set the HTTP status code, then chain res.json() or res.send() to send the error message to the client.

  • code: HTTP status code like 400, 404, 500
  • res.json(): sends a JSON response
  • res.send(): sends a plain text or HTML response
javascript
res.status(404).json({ error: 'Resource not found' })
💻

Example

This example shows an Express route that returns a 404 error response when a user is not found.

javascript
import express from 'express';
const app = express();

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  // Simulate user lookup
  const user = null; // user not found

  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  res.json({ id: userId, name: 'John Doe' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
When accessing /user/123, the server responds with status 404 and JSON: {"error":"User not found"}
⚠️

Common Pitfalls

Common mistakes include forgetting to set the status code, which defaults to 200 OK, or sending multiple responses causing errors.

Always use return before res.status().json() to stop further code execution.

javascript
/* Wrong way: missing status code and no return */
app.get('/wrong', (req, res) => {
  res.json({ error: 'Something went wrong' });
  res.send('This will cause an error');
});

/* Right way: set status and return */
app.get('/right', (req, res) => {
  return res.status(500).json({ error: 'Server error' });
});
📊

Quick Reference

Use these common HTTP status codes for errors:

Status CodeMeaningWhen to Use
400Bad RequestClient sent invalid data
401UnauthorizedAuthentication required or failed
403ForbiddenClient not allowed to access resource
404Not FoundResource does not exist
500Internal Server ErrorServer encountered an error

Key Takeaways

Always set the HTTP status code with res.status() before sending the response.
Use res.json() to send error details in JSON format for easy client parsing.
Return the response to prevent further code execution and avoid errors.
Common error codes include 400, 401, 403, 404, and 500 for different error types.
Clear error messages help clients understand what went wrong.