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 and keywords.

Example fetch usage

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

Notice that the is available on the response type.

Fetch and error handling

The MailSlurp NPM package uses to call the MailSlurp email API. Fetch throws exceptions for HTTP response status codes that are 400 or greater.

  • (400, 404...) response codes indicate a client error. Access the error message on the response body
  • (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 around MailSlurp methods and use to access the exception error message and to access the status code.

Using promise then and catch

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