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.