Rate this post

 

How to catch Magento Rest API error in Javascript
How to catch Magento Rest API error in Javascript

Hello,

Today we will learn how to catch Magento Rest API error in Javascript with these steps:

  1. Use mage/storage to call Magento rest api
  2. Change the Magento configuration
  3. Change the sku parameter in serviceUrl

 

How to Catch Magento Rest API Error in Javascript

I’ll use mage/storage to call Magento rest api: /rest/V1/products/MH01

This API will return the information of product which has SKU as MH01.

 

Let I explain the commands above:

  • serviceUrl: the full magento rest api url
  • storage: function in Magento js lib
  • storage.get(): call rest api using HTTP GET
  • done(): this function will be called after API returned success result.
  • fail(): this function will be called after API returned error/ fail result.
  • console.log(response): print the response in console of browser.

 

After run this example command in frontend of Magento, I got result below:

 

 

 

Let I explain this result:

  • readyState:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

 

  • status: the HTTP status code

401: UNAUTHORIZED

 

  • statusText: the error message

 

This result tell me that I have no permission of view information of a product. I’ll try to change the Magento configuration in: Stores/ Configuration/ Magento Web Api/ Web Api Security, set Allow Anonymous Guest Access to Yes. Then I try to run the Api call again. I got the detail product information:

 

 

Then I change the sku parameter in serviceUrl

 

 

I got the result below

 

 

The HTTP code is 404 (NOT_FOUND)

The error message is: Requested product doesn’t exist

Done! You have just learn  How to Catch Magento Rest API Error in Javascript in just 5 minutes right? Follow us to get more tips and trick about Magento 2

Common Error HTTP Codes in Magento Rest API
Create composer.json File to Upload Magento 2 Extensions to Marketplace

Leave a Reply

Your email address will not be published. Required fields are marked *