0
0
Node.jsframework~5 mins

Error response formatting in Node.js

Choose your learning style9 modes available
Introduction
Error response formatting helps your app send clear and consistent messages when something goes wrong. It makes it easier for users and developers to understand the problem.
When your server needs to tell the client about a problem like missing data.
When you want to keep error messages consistent across your app.
When you want to include helpful details like error codes or suggestions.
When debugging issues by logging clear error information.
When building APIs that other programs will use and expect structured errors.
Syntax
Node.js
res.status(statusCode).json({ error: { message: 'Error message', code: 'ERROR_CODE' } })
Use res.status() to set the HTTP status code before sending the response.
Send error details inside a JSON object for easy reading and parsing.
Examples
Sends a 404 error with a message and code.
Node.js
res.status(404).json({ error: { message: 'Not found', code: 'NOT_FOUND' } })
Sends a 400 error when user input is wrong.
Node.js
res.status(400).json({ error: { message: 'Invalid input', code: 'BAD_REQUEST' } })
Sends a 500 error for unexpected server problems.
Node.js
res.status(500).json({ error: { message: 'Server error', code: 'INTERNAL_ERROR' } })
Sample Program
This Express app checks if the user ID is a number. If not, it sends a 400 error with a clear message. If the user ID is not '123', it sends a 404 error. Otherwise, it returns user data.
Node.js
import express from 'express';
const app = express();

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  if (!userId.match(/^\d+$/)) {
    return res.status(400).json({ error: { message: 'User ID must be a number', code: 'INVALID_ID' } });
  }
  // Simulate user not found
  if (userId !== '123') {
    return res.status(404).json({ error: { message: 'User not found', code: 'USER_NOT_FOUND' } });
  }
  res.json({ id: userId, name: 'Alice' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes
Always set the correct HTTP status code to match the error type.
Keep error messages simple and helpful for users and developers.
Use consistent error codes to make it easier to handle errors in client apps.
Summary
Format error responses as JSON with a clear message and code.
Use HTTP status codes to indicate the type of error.
Consistent error formatting improves user experience and debugging.