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.
Related
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('"')
);
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.
so i'm working with Joi for validation, and i've encountered this error when trying to post with postman.
i'm follwing a tutorial, i tried to write it differently, but still have the same issue.
i'm trying to access the error message. ( first selecting the error, then the details, then the message )
in the tutorial, it looks like this
res.send(error.details[0].message)
i can see the error, but once i select details, the response is empty.
let me know if you need anything else.
Thank you in advance.
The Lord be with you and save you all, your families and friends :)
It seems like error does not have a property called details. That's why error.details is undefined. Thus, when trying to access the element of the first index of the value undefined you'll get an error.
To fix:
Make sure the error object contains a property details of type Array
If error.details will depend on other code blocks (sometimes it is defined, sometimes it isn't), you can add a ternary expression to tell your code what to in case error.details is indeed undefined.
Example:
err.details ? res.send(error.details[0].message) : res.send("error")
Which translates to
if (err.details) { // if defined
res.send(error.details[0].message) // Send the message from the error
} else {
res.send("error") // Send a general message
}
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.
Only at the checkout and on individual product pages I am getting the following error in the console log:
VM35594:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at run (layout.min.js:9)
at app.min.js:1
at main.min.js:2
at Object.execCb (require.min.js:112)
at Module.check (require.min.js:56)
at Module.<anonymous> (require.min.js:72)
at require.min.js:11
at require.min.js:74
at each (require.min.js:3)
I am using a one page checkout extension, but when I disable that the error still shows. I thought it might had something to do with the reviews on the product page (as I moved the reviews out of the tabs), but undoing that change didn't fix the error on the product pages.
Try this in the console:
JSON.parse(undefined)
Here is what you will get:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at <anonymous>:1:6
In other words, your app is attempting to parse undefined, which is not valid JSON.
There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).
window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn) // oops, misspelled!
The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.
Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.
As #Seth Holladay #MinusFour commented, you are parsing an undefined variable.
Try adding an if condition before doing the parse.
if (typeof test1 !== 'undefined') {
test2 = JSON.parse(test1);
}
Note: This is just a check for undefined case. Any other parsing issues still need to be handled.
localStorage.clear()
That'll clear the stored data. Then refresh and things should start to work.
Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.
Example for Google Chrome:
F12
Application
Local Storage
Clear All
For me, that happened because I had an empty component in my page -
<script type="text/x-magento-init">
{
".page.messages": {
"Magento_Ui/js/core/app": []
}
}
Deleting this piece of code resolved the issue.
This is due to the interfering messages that come on to the page. There are multiple frames on the page which communicate with the page using window message event and object. few of them can be third party services like cookieq for managing cookies, or may be cartwire an e-com integration service.
You need to handle the onmessage event to check from where the messages are coming, and then parse the JSON accordingly.
I faced a similar problem, where one of the integration was passing a JSON object and other was passing a string starting with u
If you get Uncaught SyntaxError: Unexpected token u in JSON at position 0 then you could do the following quick checks:
jsObj = JSON.parse(data)
data - check the data is undefined or not
data - check the data is a valid JSON string or not
data - check the data is corrupted by unwanted whitespace or not
data = data.trim(); // remove the unwanted whitespace
jsObj = JSON.parse(data);
data - check the received data uses the correct encoding format('utf8', 'utf16le', 'ucs2') or not
fs.readFile(file, 'utf8', function(err, data) { ... });
fs.readFile(file, 'utf16le', function(err, data) { ... }); // le - little endian
fs.readFile(file, 'ucs2', function(err, data) { ... }); // kind of 'utf16le'
I had this issue for 2 days, let me show you how I fixed it.
This was how the code looked when I was getting the error:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.response);
console.log(data)
}
This is what I changed to get the result I wanted:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.responseText);
console.log(data)
}
So all I really did was change
this.response to this.responseText.