MailSlurp logo

blog

Fetch error message in JavaScript

Error Handling with Javascript Fetch: A guide on how to handle different response status codes in API design using try-catch keywords and promises with samples.

Response status codes are an important part of API design. They can inform a caller about why a request may have succeeded or failed. When using Javascript fetch to make HTTP requests an exception is thrown for network failures. For non-2xx responses, check response.ok and handle status codes directly so your app does not crash unexpectedly.

Example fetch usage

You can call any URL using fetch in a browser console.

$ await fetch('google.com')
> Response { type: "basic", url: "https://www.mailslurp.com/google.com", redirected: false, status: 404, ok: false, statusText: "Not Found", headers: Headers, body: ReadableStream, bodyUsed: false }

Notice that the status is available on the response type.

Fetch and error handling

The MailSlurp NPM package uses fetch to call the MailSlurp email API. Handle non-2xx HTTP responses by checking response.ok and reading the body/status for diagnostics.

  • 4xx (400, 404...) response codes indicate a client error. Access the error message on the response body
  • 5xx (500, 501...) response codes indicate a server error. If encountered please contact support.

Catch exceptions

Any non-2xx response throws an exception. There are valid 404 responses that you should handle, these include the 404 returned from methods when a requested resource can't be found.

Use try{}catch(e){} around MailSlurp methods and use await e.text() to access the exception error message and e.status to access the status code.

describe("handling mailslurp errors", () => {
  test("try catch and read error", async () => {
    try {
      await mailslurp.inboxController.sendEmailAndConfirm("badInboxId", {});
    } catch (e) {
      // handle the error and status code in your code
      // 404 is returned when emails cannot be found for a given condition for instance
      const message = await e.text();
      const statusCode = e.status;
      // test action
      expect(e.status).toEqual(400);
      expect(message).toContain("Invalid ID passed");
    }
  });
});

Using promise then and catch

You can also handle fetch exceptions using the older Promise then and catch methods.

fetch("notfound").catch((e) => console.log(e.status === 404));
// true

Production fetch error-handling checklist for email APIs

Use this flow to move from ad-hoc fetch checks to reliable delivery testing.