Fetch error message javascript

Handle response exceptions with Fetch in Javascript

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 any response with a code of 400 or more. This will cause a calling function to crash but luckily we can easily handle the situation with Javascripts try and catch keywords.

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. Fetch throws exceptions for HTTP response status codes that are 400 or greater.

  • 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(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

Ready to dive in?Start building email applications today.