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

Related content

NodeJS MailSlurp SDK

Nodemailer alternatives to send and receieve email in code and tests

Fastest way to start a typescript project

Modern typescript tooling has come a long way. See how to setup a new project with TS-Node, TSC, and typeconfig.json.

Fetch error message javascript

Handle response exceptions with Fetch in Javascript

GraphQL API disposable email accounts

How to create real email addresses using GraphQL to send and receive emails in tests and frontend applications.

GraphQL Email API Tutorial

Did you know you can send and receive emails using GraphQL?

Hugo responsive image srcsets

Serve responsive picture tags with custom render-image layout partial in Hugo static site generator.

How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

NodeMailer NPM Tutorial

Send and receive email using NodeMailer in Node JS.

Create custom print classes with Tailwind

Configure tailwind.config.js to create prefixed classes with a custom media query.

CypressJS Example

Test email sign-up. password verification and more with Cypress JS and MailSlurp.

CypressJS Email Testing

Use real email accounts in CypressJS to test user sign-up, email verification, and more.

Send email with Axios JS (and receive email too!)

Send email in Javascript with MailSlurp email API

Jest, Puppeteer

Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.

Webdriver, JS, WDIO

Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.

TestCafe end-to-end MFA testing for user sign-up and email verification

End-to-end testing with MailSlurp, NodeJS, and TestCafe.

Base64 file uploads

How to encode files as Base 64 encoded strings in several languages

Deno Email Apis

Send and receive emails in Deno JS. Use APIs in Deno with MailSlurp.

Email read (opened seen settings)

How to control the seen or read settings for an email using MailSlurp.

GraphQL Email API

Fetch and read emails with GraphQL inboxes using MailSlurp email API.

Testing OTP password link username and password for 2 factor authentication (2FA)

Testing OTP password link username and password for 2 factor authentication (2FA)

MailSlurp NodeMailer SMTP Usage

Use SMTP nodemailer with MailSlurp disposable email addresses

Testing email with Cypress test email accounts

Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.

Send emails in NodeJS using SMTP

How to use Javascript SMTP client (or Nodemailer) to send email with MailSlurp mail server

Testing Email with Cypress JS and MailSlurp

Email testing with Cypress JS

Ready to dive in?Start building email applications today.