#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 13 of 28medium

How should you handle errors in APIs?

Best practices for API error handling.

What You'll Learn

  • Error response structure
  • Common error types
  • Implementation patterns

Error Response Structure

code.jsJavaScript
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      { "field": "email", "message": "Invalid email format" },
      { "field": "password", "message": "Must be at least 8 characters" }
    ]
  }
}

Common Error Codes

StatusCodeDescription
400BAD_REQUESTInvalid request syntax
401UNAUTHORIZEDAuthentication required
403FORBIDDENNo permission
404NOT_FOUNDResource not found
422VALIDATION_ERRORValidation failed
429RATE_LIMITEDToo many requests
500INTERNAL_ERRORServer error

Implementation

code.jsJavaScript
// Custom error class
class ApiError extends Error {
  constructor(statusCode, code, message, details = null) {
    super(message);
    this.statusCode = statusCode;
    this.code = code;
    this.details = details;
  }
}

// Usage
throw new ApiError(404, 'NOT_FOUND', 'User not found');

// Error middleware
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: false,
    error: {
      code: err.code || 'INTERNAL_ERROR',
      message: err.message,
      details: err.details,
    },
  });
});