I am using rails on the backend and vue.js on the front end. I am trying to print the error in case there is any. Under the .catch I have got the error as below but cannot fetch the message from it. Kindly help me resolve it.
.catch(function (error) {
debugger
});
In the console, if I try error.response.data.error this returns '{:message=>"Amount is less than the minimum value"}' I am not able to figure out how I can fetch just the message.
Error Answer
Your baclend is not serializing object correctly. So message is a part of a string instead of JSON property. If you don't want to change that you can use
const message = error.response.data.error.substring(
str.indexOf('"') + 1,
str.lastIndexOf('"')
);
Related
I'm using npm yahoo-finance to fetch stock data. When I input a stock symbol that doesn't exist, I would like to catch the error.
const yahooFinance = require('yahoo-finance');
async function stockData() {
try {
let data = await yahooFinance.historical({symbol: "SIJGAOWSFA", from: 2020-08-23, to: 2021-08-23});
} catch (error) {
console.error(error)
}
}
stockData();
However it doesn't appear to be a typical fetch error. It's not being caught at all. By that I mean, the error you see below was not logged to the console via the console.error(error). Rather something outside the scope of this file is logging the error. When the error occurs, nothing in catch is executed.
I plan on using this in a for loop, so would like to catch the error so I can avoid executing any following functions.
A collaborator says that:
Is this from an existing project that was working and stopped working, or a new project?
If the former - everything is still working fine on my side. (Very) occasionally there are issues at yahoo that get stuck in their cache, possibly relating to DNS too. I'd suggest to clear your DNS cache and also try querying different data to see if that works.
If the latter (new project), it could be the data you're querying. Try query different data and see if it works. Usually yahoo throws back a specific error if something wrong, but it could be this.
If neither of those approaches work, but you still need to catch this sort of error, given the source code, what it does is:
if (!crumb) {
console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
And then continues on as normal (without throwing), and eventually returns an empty array.
If you're sure the result should contain at least one item, you can check to see if it's empty, and enter into an error state if it is.
Otherwise, if you don't know whether the array should contain values or not, another option is to overwrite console.warn so that you can detect when that exact string is passed to it.
Another option would be to fork the library so that it (properly) throws an error when not found, instead of continuing on and returning an empty array, making an empty successful result indistinguishable from an errored empty result. Change the
if (!crumb) {
console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
to
if (!crumb) {
throw new Error('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
and then you'll be able to catch it in your call to .historical.
I'm trying to call the API but it doesn't return me anything.
I'm calling it like: res.on('data', d => { const RetrieveFromApi = JSON.parse(d).FLUX.quote.USD.price;.
The API is successfully called since I can see it in the API history, and data is defined as d.
Can you help me please?
from your screen provided in comment, you passed one property you don't access to it which is data
So just add property data before FLUX
JSON.parse(d).FLUX.quote.USD.price;
^data.FLUX.quote.USD.price;
From the image of the log the object seems incomplete at the end, did you try to use JSON.stringify(d) to see if there are any errors on the json object? or copy the response on https://jsonlint.com to check?
Because the error message points that the parse doesn't find a valid json object, maybe that is the whole point.
And the other tip is to try to store the value of JSON.parse in an variable before trying to access his values.
Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})
I'm getting this error "TypeError: Cannot read property '0' of undefined" when I want to extract a data from JSON file.
However, the data I want to extract is not available every time I request a JSON file, therefore, I'm getting this error which makes my Node.js Application to crash every time I'm getting this error.
simply check if it exists or not:
if (json && json['Name'] && json['Name']['Nationality']) {
data = json['Name']['Nationality'][0];
} else {
// no data, do whatever error handling you want here
}
A solution for this sort of problem is using try-catch:
try {
data = json['Name']['Nationality'][0];
} catch (error) {
data = "Sorry no data found"
}
The try function is going to run the code if it did find any error it will pass it to catch.
I am using a third party database which has a rest API. When I make a call I get an error back (which I am expecting in my case):
transaction.commit(function(err) {
if (err){
var par = JSON.parse(err); \\ returns error: SyntaxError: Unexpected token E in JSON at position 0
console.log(JSON.stringify(err));
console.log(err);
console.log('' + err);
//First console.log return: {"code":409,"metadata":{"_internal_repr":{}}}
//Second console.log return: { Error: entity already exists: app: "s~myapp"<br/>path <<br/> Element {<br/> type: "v"<br/> name: "bob#gmail.com"<br/> }<br/>><br/>
//Third console.log returns: Error: entity already exists: app: "s~myapp"<br/>path <<br/> Element {<br/> type: "v"<br/> name: "bob#gmail.com"<br/> }<br/>><br/>
}
{);
I need to extract the error field and the type field. I have tried to parse the JSON and then go par.error or par.type to get the variables, but I can't parse the object because I get an error.
You're apparently having an Error object, that has a message property to extract the message string.
Hence use
err.message
to obtain it.
References:
Error.prototype.message
Error
Based on your results, it seems that the err parameter that you're getting is already an object and not a JSON string, so you don't need to parse it at all.
You should be able to get err.code without problem.
You did mention that you need to get the error type -- but that seems to not be available in that object at all (and that's why you'd get undefined while you tried it.
However, by using err.Error you should be able to get the error string.
If you're unsure of what data the object has, you can try the following:
Execute console.dir(err) -- this should give you a good understanding of what the err object contains.
Just debug up to that point and look around in the err object.
(Best option) Check the platform's / libraries API documentation, it should tell you what error information it returns so you can use exactly that.