Unable to catch error when fetching data in async function - javascript

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.

Related

matrix-js-sdk setup and configuration

I am having some issues trying to connect to a matrix server using the matrix-js-sdk in a react app.
I have provided a simple code example below, and made sure that credentials are valid (login works) and that the environment variable containing the URL for the matrix client is set. I have signed into element in a browser and created two rooms for testing purposes, and was expecting these two rooms would be returned from matrixClient.getRooms(). However, this simply returns an empty array. With some further testing it seems like the asynchronous functions provided for fetching room, member and group ID's only, works as expected.
According to https://matrix.org/docs/guides/usage-of-the-matrix-js-sd these should be valid steps for setting up the matrix-js-sdk, however the sync is never executed either.
const matrixClient = sdk.createClient(
process.env.REACT_APP_MATRIX_CLIENT_URL!
);
await matrixClient.long("m.login.password", credentials);
matrixClient.once('sync', () => {
debugger; // Never hit
}
for (const room of matrixClient.getRooms()) {
debugger; // Never hit
}
I did manage to use the roomId's returned from await matrixClient.roomInitialSync(roomId, limit, callback), however this lead me to another issue where I can't figure out how to decrypt messages, as the events containing the messages sent in the room seems to be of type 'm.room.encrypted' instead of 'm.room.message'.
Does anyone have any good examples of working implementations for the matrix-js-sdk, or any other good resources for properly understanding how to put this all together? I need to be able to load rooms, persons, messages etc. and display these respectively in a ReactJS application.
It turns out I simply forgot to run startClient on the matrix client, resulting in it not fetching any data.

How to separate caught errors based on their OPCODE (discord.js)

So basically, I have a bot that part of its functionality is to create channels inside of a guild (discord server.) I have the generic error handlers, and catch blocks, but what I am wondering is how to separate the error 'Maximum number of guild channels reached (500)' of opcode '30013,' so that if that is the error, it display a message saying the maximum amount of channels has been created, as well as allowing for the other errors to get caught.
Ideally all errors can still get caught, but if the error is the desired error, it will do what I ask, instead of simplifying the error JSON response, like the error handler make it do.
Something alone these lines should work if the error response received matches this link.
try {
// You code here
}
catch(err) {
if (err.code == 30013) {
// feedback code here
}
}
As I'm not sure if you are using async or not I'm presenting the standard try/catch format vs .catch. Regardless the logic should be the same.
Inspect the error object and see what property distinguishes it from others (most likely its code property). Once you know, check the property in your catch block against the desired one. If it matches, continue with your specific code.

Understanding anonymous functions in Express js

I am new to express and am trying to wrap my head around callbacks in RESTful actions. In my PUT request below, I'm confused about the following line that I have bolded below. Why is response.pageInfo.book being set to the second parameter in the anonymous function (result)? that seems kind of arbitrary.
Also, what is the best way to inspect some of these parameters (req, res, result, etc)? When I console.log it, doesn't show up in my terminal or in my browser console.
exports.BookEdit = function(request, response) {
var id = request.params.id;
Model.BookModel.findOne({
_id: id
}, function(error, result) {
if (error) {
console.log("error");
response.redirect('/books?error=true&message=There was an error finding a book with this id');
} else {
response.pageInfo.title = "Edit Book";
**response.pageInfo.book = result;**
response.render('books/BookEdit', response.pageInfo)
}
})
}
The findOne function takes a query ({_id : id}) and a callback as arguments. The callback gets called after findOne has finished querying the database. This callback pattern is very common in nodejs. Typically the callback will have 2 arguments
the first one error is only set if there was an error.
the second one usually contains the value being returned. In this case you are finding one book in the database.
The line you have bolded is where the book object is assigned to a variable which will be sent back to be rendered in the browser. It is basically some javascript object.
Your second request, to debug this stuff, here is what you can do:
In you code type the word debugger;
e.g.
var id = request.params.id;
debugger;
Next, instead of running your program like this:
node myprogram.js
... run with debug flag, i.e.
node debug myprogram.js
It will pause at the beginning and you can continue by pressing c then Enter
Next it will stop at that debugger line above. Type repl and then Enter and you'll be able to inspect objects and variables by typing their names.
This works very well and requires no installation. However, you can also take a more visual approach and install a debugger such as node-inspector which does the same thing but in a web browser. If you use a good IDE (e.g. webstorm) you can also debug node.js pretty easily.
In the above, the document that is the result of the findOne() query is being added to the pageInfo key of the response and is then being rendered in a template. The first parameter is a potential error that must be checked and the remainder contain data. It's the standard node idiom that an asynchronous call returns to a callback where you do your work.
The writer of the code has also decided to decorate the response object with an extra attribute. This is often done when a request passes through a number of middleware functions and you might want to build up the response incrementally (for example having a middleware function that adds information about the current user to the pageInfo key).
Look and see what else is on response.pageInfo. Information was probably put there by previous middleware (especially since the function above expects the pageInfo key to exist). Just do a console.log(response.pageInfo) and look on your server log or standard out.

Node.js: Get "Trying to open unclosed connection" when calling method from child process

I'm getting the "Error: Trying to open unclosed connection," but I don't believe it's due to a db issue... and that's why I'm stumped. Most solutions to this error, reference db connection issues.
My goal here is execute an external process. If the process closes with anything other than exit code 0, I want to email an alert for example.
I was using the child.on('close', function(code).... to get the exit value from the external process (coming back as "code") So if code !=0 I want to do something... maybe rerun the test... maybe call a different method that sends an email, etc.
Each time I attempt to call a method, from within child.on('close'), I get the error "Trying to open unclosed connection." Which is why I'm also handling the save action in the same block.
Code Sample:
var spawn = require('child_process').spawn,
child = spawn('sipp', ['-s', dnis,server, '-sn', scenario, '-m', '1','-i','127.0.0.1','-recv_timeout','1000']);
}
child.on('close',function(code){
if(code != 0){
Call().emailAlert(dnis, server, scenario, type, carrier);
}
var TestResults = mongoose.model('test_results', TestResultsSchema);
// Saving results to MongoDB
var result = new TestResults({
testType: type,
dnis: dnis,
server: server,
result: code,
carrier: carrier,
date: Date.now()
});
result.save(function (err) {if (!err) {console.log ('Successful Save!')}
else{console.log(err)}});
});
};
If I remove:
if(code != 0){
Call().emailAlert(dnis, server, scenario, type, carrier);
}
The error goes away. What's the best way for me to capture the exit code of the process, and based on it, make a call to a different method (i.e. to email an alert) in Node.js?
I guess I was wrong. I changed the mongoose.connect to mongoose.createConnection and this specific error went away... but unfortunately I'm left with more errors. I'll open up the main question in a different topic.

Specify a sanitized error when a Meteor check fails

I using check to verify arguments to my meteor methods. I would like to send a helpful error message when the check fails.
Is there a way to specify a sanitized error to send to the client when the check fails?
I could wrap the check in a try/catch block and generate another Meteor error, but this seems needlessly verbose.
The only way to do it I figured so far is to put your check inside of try catch block and then throw new exception with reason/message taken from original one. Not perfect, even ugly, but works for now.
try {
check(param, String)
} catch (ex) {
let message = ex.message.startsWith('Match error: Match error: ')
? ex.message.slice(26, ex.message.length)
: ex.message
throw new Meteor.Error(400, message)
}

Categories

Resources