Error Handling in REST APIs

Last Updated : 27 Jan, 2026

Effective error handling in REST APIs ensures clear communication, predictable behavior, and better debugging between the client and server.

  • Validate requests to catch client-side errors early.
  • Use appropriate HTTP status codes to reflect the error type.
  • Send clear and consistent error messages in responses.
  • Handle server-side failures to prevent unexpected crashes.

Concepts of Error Handling

Concepts of Error Handling focus on identifying, managing, and responding to errors in a structured way to ensure reliable and predictable API behavior.

When an Error Occurs

  • Validate required data before processing the request.
  • Reject requests with missing or invalid fields.

Responding with Errors

  • Stop execution immediately if validation fails.
  • Return a meaningful error message to the client.
  • Use simple checks (e.g., if (!data.name)) to enforce validation.

Using HTTP Status Codes

HTTP status codes help indicate the status of a request and whether it was successful or encountered an error. Here are some commonly used HTTP status codes and their meanings:

  • 200 - OK: The request was processed successfully.
  • 201 - Created: A new resource was successfully created (e.g., a user).
  • 400 - Bad Request: The request is invalid or missing required data.
  • 422 - Unprocessable Entity: The request is well-formed but contains invalid data.
  • 500 - Internal Server Error: An unexpected error occurred on the server.

How to Handle Errors

Creating a New Resource (e.g., Creating a New User)

When a new resource is being created, such as a user or a session, ensure the required data is provided. For example:

  • If required data (such as a name) is missing or invalid, return 400 Bad Request or 422 Unprocessable Entity.
  • If everything is fine, respond with 201 Created and provide the created resource's details.

If you are using Node.js with Express to handle the API requests, you can use the following approach:

Node
// Check if name is provided
if (!data.name) {
  return res.status(422).json({ message: "Name is required." });
}
// Proceed with creation and return success message
res.status(201).json({ message: "User created successfully." });

Error During Parsing or Server Issues

Server-side failures, such as parsing errors or internal malfunctions, should be reported using 500 Internal Server Error to indicate the issue is not caused by the client.

  • Used for unexpected server-side failures.
  • Indicates errors during data parsing or processing.
  • Informs the client that the server could not complete the request.
  • Helps separate client errors (4xx) from server errors (5xx).
Node
try {
  // Your code here, such as parsing data or interacting with the database
} catch (err) {
  res.status(500).json({ message: "Something went wrong. Please try again later." });
}

Using Try-Catch Blocks for Error Handling

In JavaScript (Node.js), you can use try-catch blocks to handle errors that may occur during the execution of API requests.

  • Try Block: The code that may cause an error is placed inside the try block.
  • Catch Block: If an error occurs, it is caught in the catch block, where you can respond with an error message.
Node
app.post('/create-user', (req, res) => {
  try {
    const data = req.body;
    if (!data.name) {
      throw new Error("Name is required.");
    }
    // Proceed to create user in the database
    res.status(201).json({ message: "User created successfully." });
  } catch (err) {
    res.status(500).json({ message: err.message || "Something went wrong." });
  }
});

Status Codes Based on Error Types. 500 is only for server errors.

HTTP Status Codes for Error Handling

HTTP status codes indicate whether a request succeeded or failed and why.

  • 1xx – Informational: Request received, processing continues.
  • 2xx – Success: Request processed successfully.
  • 3xx – Redirection: Further action required by the client.
  • 4xx – Client Error: Invalid or malformed request.
  • 5xx – Server Error: Server failed to process the request.

Example: Handling a Missing Name in POST Request.

Node
app.post('/create-user', (req, res) => {
  const data = req.body;
  if (!data.name) {
    return res.status(422).json({ message: "Name is required." });
  }
  // Code to create user if name is provided
  res.status(201).json({ message: "User created successfully." });
});

Enhanced Error Handling with Throwing Errors

Enhanced error handling allows you to throw custom errors when request data is invalid or incomplete, ensuring clear and controlled API responses.

  • Improves validation and control over request processing.
  • Helps return clear and consistent error responses to the client.
Node
app.post('/create-user', (req, res) => {
  try {
    const data = req.body;
    if (!data.name) {
      throw new Error("Name is required.");
    }
    // Proceed with creation
    res.status(201).json({ message: "User created successfully." });
  } catch (err) {
    res.status(500).json({ message: err.message || "Something went wrong." });
Comment

Explore