How to recover and gracefully handle failed API request to a third party API

42 Views Asked by At

I created a few functions that send requests to a third party API (canvas lms) to make basic CRUD operations.

I need to add a user to a "section". A 404 is thrown if I try to add a user to a section that doesn't exist. In addition if I try to GET the section (before adding the user) if the section doesn't exist the GET request will also throw a 404.

I don't know a strategy on how to handle this sequence properly (I find myself running into this a lot with various third party APIs). Here is my approach:

const addUserToSection = async (sectionId, userId) => {
  try {
    await createSectionEnrollment(sectionId, userId);    
  } catch (error) {
    if (error.response.status === 404) {
      try {
        await createCanvasCourseSection({
          name: 'Section A',
          sectionId: 'sectionA',
          start: '2024-01-01',
          end: '2024-12-31',
          courseId: 5
        });
        return createSectionEnrollment(sectionId, userId);
      } catch (error) {
        console.error(error.response.message);
      }
    }
    console.error(`error message: ${error.response.message}`)
  }
};

Here are some of the functions:

const axios = require('axios');
const headers = {
  'content-type': 'application/json',
  Authorization: `Bearer API KEY HERE`
};

const baseUrl = 'https://canvas.instructure.com/api/v1'; // not a real canvas url

const createUserSectionEnrollment = async (canvasShellId, userId, notify = false) => {
  const url = `${baseUrl}/sections/${canvasShellId}/enrollments`;
  return axios({
    method: 'post',
    url,
    headers,
    data: {
      enrollment: {
        user_id: userId,
        type: 'StudentEnrollment',
        notify,
        enrollment_state: 'active',
        limit_privileges_to_course_section: true
      }
    }
  });
};

const createCourseSection = async ({ sectionName, canvasShellId, courseId }) => {
  const url = `${baseUrl}/courses/sis_course_id:${courseId}/sections`;
  return axios({
    method: 'post',
    url,
    headers,
    data: {
      course_section: {
        name: sectionName,
        sis_section_id: canvasShellId
      }
    }
  });
};

In the code above, I take the approach of trying to add a user to a section, knowing there is a chance the section doesn't exist. If the error message is a 404, I assume (which may not be the right assumption) that the section doesn't exist so I create the section and try again to add the user to the section.

Instead of trying to add the user directly, I could check if the section exists, but that will also throw an error if it doesn't exist, so I'd hit the catch block either way if it didn't exist.

Is it okay to handle and create the section in the catch block? Countless tutorials and code snippets leave comments in the catch statements that say "handle error here", unfortunately, this isn't basic knowledge to me and I can't find code examples that handle errors.

If anybody can demonstrate how to handle this situation or a codebase that has these type of CRUD API requests to a third party library which demonstrates how to handle errors it would be a huge help.

0

There are 0 best solutions below