A guide on unpacking errors returned from a backend and sent out as an Error object in JavaScript

After investigating, it turns out that the issue lies with how the Error object constructor handles the response object passed to it in the catch error handler.

The SDK I am using contains a method which can be found at this link to sdk code

    /**
     * Axios request
     * @param method Request method
     * @param url Server URL
     * @param requestConfig Custom Axios config
     */
    async request(method, url, requestConfig) {
        try {
            const response = await this.axios.request(Object.assign({ method,
                url }, requestConfig));
            return response.data;
        }
        catch (error) {
            if (error.response) {
                throw new Error(error.response.data.message);
            }
            else {
                throw error;
            }
        }
    }

I am trying to handle the errors generated by this method. The second case where we use throw error; is not an issue for me. However, extracting the message from the first case -

throw new Error(error.response.data.message);
is proving difficult.

When I debug the error using console.log("Error: ", error);, the output shows as Error: Error: [object Object] in the console.

If I check

console.log('sdk => error.response.data.message: ', error.response.data.message);
before triggering the error, it displays:

sdk => error.response.data.message:  
[{…}]
0:
messages: Array(1)
0: {id: "Auth.form.error.user.not-exist", message: "This email does not exist."}
length: 1
__proto__: Array(0)
__proto__: Object
length: 1
__proto__: Array(0) 

Possibly, the root of the problem is that the Error constructor expects a string and hence executes the toString() method on the object.

This is the response visible in the NETWORK tab of the Inspecting Tool:

{"statusCode":400,"error":"Bad Request","message":[{"messages":[{"id":"Auth.form.error.user.not-exist","message":"This email does not exist."}]}]}

Currently, I can only access and output: error.message[0] Attempting to access error.message[0].messages results in undefined.

Trying:

const errorToJSON = JSON.parse(error)
throws the following error:

Unhandle Rejection (SyntaxError): Unexpected token E in JSON at position 0

My objective is to retrieve the textual content of the message: "This email does not exist."

Thank you in advance.

Answer №1

Understanding the object's structure is key when extracting data from it. Mimicking the response object is crucial for successful data extraction.

error represents the object caught within a try/catch block

error.response holds the response data

error.response.data contains the JSON return data

error.response.data.message is an array of messages

In the code snippet below, a new Error object is thrown with the messages array passed to its constructor. The issue arises because the Error object's constructor requires a type of variable that is a String.

To resolve this problem, one solution is to utilize JSON.stringify on the messages array and pass it into the Error object constructor. Another option would be to directly throw the error.response.data.message object. It's up to you to determine which approach suits your project best.

Here is how the stringify method can be used:

if (error.response) {
  throw new Error(JSON.stringify(error.response.data.message));
}

Check out this example showcasing throwing the messages array:

if (error.response) {
  throw error.response.data.message;
}

Answer №2

To convert a string response into a JSON object, you can utilize the JSON.parse() function available in JavaScript.

After converting the response to JSON format, you can easily access the value by navigating through the response:

var errorMessage = response.message[0].messages[0].message;

Answer №3

According to epascarello, extracting your error message can be done using

error.message[0].messages[0].message
. Take a look at the demonstration below:

const error = {"statusCode":400,"error":"Bad Request","message":[{"messages":[{"id":"Auth.form.error.user.not-exist","message":"This email does not exist."}]}]}

console.log(error.message[0].messages[0].message)

This method works due to the following explanation.

error      // Refers to the parent object where your message is stored
.message   // Retrieve the `message` parameter from the object
[0]        // Since `message` is an array, get the first object in the array
.messages  // Obtain the `messages` parameter from the object
[0]        // Since `message` is also an array, fetch the first object in the array
.message   // Get the value of the `message` parameter

{                                                 <------ error
  "statusCode":400,
  "error":"Bad Request",
  "message":[                                     <------ .message
    {                                             <------ [0]
      "messages":[                                <------ .messages
        {                                         <------ [0]
          "id":"Auth.form.error.user.not-exist",
          "message":"This email does not exist."  <------ .message
        }
      ]
    }
  ]
}

It's important to note that this approach will only work if both the `message` and `messages` Arrays contain elements. If uncertain, you can utilize something like

error.message.flatMap(msg => msg.messages.map(innerMsg => innerMsg.message))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to merge two JSON arrays using Axios in a React project?

I am currently working on getting data using axios React from Laravel, but I am facing some challenges in combining two arrays by their respective Ids. In my case, I am trying to retrieve product data and images from the Laravel Controller. Can anyone prov ...

Unable to close expanded grid item using close button

Currently, I am working on a simple 3 column grid where each grid item consists of an image and a close button. The functionality I want to achieve is that when a grid item is clicked, the image should expand and the close button should become visible. Th ...

The personalized directive does not respond to modifications in attributes

I am in the process of creating a modal directive that will be used to display data tables. The directive has an attribute called modal-visible, which is initially set to false by default. If this value is true, the modal will be visible when loaded. Howev ...

A step-by-step guide to summing two numbers within a list using vue.js

How do I calculate the average of the first 5 numbers in my list taken from the URL, grouped by 5-minute intervals? I have a delay of 1 minute to ensure there are 5 values within the initial 5 minutes. After that, I want to display the averages in 3 differ ...

Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example: function keepFirst(str, substr) { ... } keepFirst("This $ is some text $.", "$"); The expected result should be: This $ is some tex ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

Switches in a React-Native ListView are not refreshing properly

Situation: I encountered an issue with a ListView of Switches Problem: The Switches are not changing state when pressed. When debugging, each switch appears to be checked momentarily after the setValue function is called, but then reverts back to unchecked ...

Interacting between Angular controllers and services to efficiently showcase JSON information

Recently, I started working with Angular 1.5+ and I'm facing some challenges with the basics, particularly when it comes to displaying data from a JSON file on the DOM. Although I can fetch the data successfully (at least I think so, as it console lo ...

How to use the ObjC RestKit library for object mapping to a JSON NSString?

I'm currently utilizing RestKit on iOS. I've set up an object and its mapping, allowing me to communicate data with the server. Now, I'd like to have the -description method of my mapped objects return the JSON mapping for easier logging to ...

What is the best method for unraveling pagination within JSON data?

I've been working on populating my website with products using the chinavasion.com API. I've managed to retrieve a list of products within a specific category, but the JSON response only includes 10 products and pagination that is confusing me. C ...

Is there a way to convert NuGet.NuGetVersion to a class in C# through deserialization?

As a novice programmer working on an application for my job, I recently encountered an issue while trying to deserialize a class. The class in question is named Nuget, and its structure is as follows: public class Nuget { public string? Name { get; set ...

Troubleshooting: Why is $watch failing to track changes on factory variables in Angular

I have created a factory named SharedService as shown below: angular.module('Fms').factory('SharedService', function() { var userdetails=false; return userdetails; }) Below controllers utilize this factory: angular.mod ...

Obtaining the value of an input field in HTML

I am currently working on a text input field that triggers a JavaScript function when a numeric value is entered. <input type="text" value="key" ng-keypress="submit(key)" ng-model="pager.page"/> Controller $scope.submit = function (val) { ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Utilizing Angular to intercept AJAX requests, verifying internet connectivity before proceeding with sending the request

In my Angular (with Ionic) app, I have this code snippet: my_app.factory('connectivityInterceptorService', ['$q', '$rootScope', function ($q, $rootScope) { var connectivityInterceptorServiceFactory = {}; var _request ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Running pug directly from the local node_modules directory

I'm currently attempting to run pug (/jade) from my node_modules directory, however I am unable to locate the executable within the node_modules/.bin folder. I am running MacOS 10.12.5 and installed pug using the "npm install --save pug" command. Is ...

Attempting to remove the current click event listener and add a new event listener

I am attempting to remove the click event binding and replace it with another click event after the button has been clicked once. <small id="selectall_agriculture" onclick="refineSearch.testing('agriculture')">(select all)</small> O ...

Having trouble getting the navigation function to work correctly for my ReactJS image slider

I am looking to create a simple image slider that contains 3 images in an array. I want to be able to navigate through the slider using just one function that can move back and forth between images. If you click "next" on the last image, it should bring ...