Lesson Overview

In this session, we're delving into error handling within Node.js and Express.js. As a robot needs instructions for instances when an object cannot be found, our code similarly requires mechanisms for handling errors.

Introduction to the Try/Catch Block

Error handling is a procedure that detects and manages errors during program execution. Unhandled errors, generated by Runtime Errors (exceptions during execution), can disrupt programs — akin to a robot attempting to find a non-existent object.

The try statement examines a block of code for errors. Any existing errors are "caught" by the catch block, thus providing error management.

try {
  // Attempts to print 'num'
  console.log(num);
} catch (err) {
  // If an error occurs (e.g., `num` wasn't defined), it's caught, and an error message is printed
  console.log(err.message);
}

In this piece of code, instead of letting the program crash (due to the issue that num is not defined), we "catch" the error and handle it gracefully.

Error Responses in API

Effective error handling enhances user experience by utilizing appropriate HTTP status codes (e.g., HTTP 200 signifies success, HTTP 404 denotes a resource not found, HTTP 500 denotes an internal server error) within the API.

// Endpoint for retrieving user data by ID
app.get('/api/user/:id', (req, res) => {
  try {
    const user = getUserById(req.params.id);
    if (!user) {
      // If the user was not found, return status 404
      res.status(404).json({message: "User not found"});
      return;
    }
    res.json(user);
  } catch (err) {
    // If an error occurs, a response with status code 500 is sent
    res.status(500).json({ error: "Server error" });
  }
});

In this context, we use try/catch for handling server-side exceptions, and catch dispatches an HTTP status code 500 (Internal Server Error) for server errors.

Error Handling in a Full-Stack Application

In a full-stack application, both client and server errors require attention.

For the server, consider the following:

// API endpoint that attempts to update a user's details
app.put('/api/user/:id', (req, res) => {
  try {
    const user = updateUser(req.params.id, req.body);
    // rest of the code
  } catch (err) {
    // If an error occurs, an error response is sent
    res.status(500).json({ error: 'Failed to update user' });
  }
});

On the client side (React with Axios), the catch block manages errors during the GET request.

import React, { useEffect } from 'react';
import axios from 'axios';

function App() {
  useEffect(() => {
    // This function will be triggered after the component is mounted
    axios.get('/api/user/123')
      .then(res => {
        // Handle success
      }).catch(err => {
        // Error during GET request is handled here
        console.error(err.message);
      });
  }, []);
 
  // Rest of the functional component code

  return (
    // Your JSX here
  );
}

export default App;
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal