require throw an error when the file doesn't exist - javascript

I'm trying to load some js files by dynamic path using require
try {
require([`views/Report/${path}/filterProps.js`], function(data) {
console.log(props);
});
} catch (error) {
console.log(error);
}
the path is a usual string (for instance 'file1')
everything is fine but when the file does not exist it thrown the error.
I have tried try-catch but it didn't solve the problem.
Any idea to solve the problem?
update
this how it worked for me:
require.onError = function(err) {
console.log(err);
};
require([`views/Report/${path}/filterProps.js`], function(data) {
console.log(props);
});

Related

How to catch error messages inside async functions correctly?

app.get('/someFunction', someFunction);
async function someFunction(req, res) {
try {
await functionWithError(parameter);
res.send('success');
} catch (err) {
console.log(err); //works
res.send(err); //does not
}
}
async function functionWithError(parameter) {
return (result = await query('SELECT * from table where column = ?', [
parameter,
]));
}
The error in functionWithError is that 'query' is not defined. In try-catch, catch fires correctly but res.send(err) is blank, however console.log(err) works.
An error object being thrown here, Should use err.name or err.message.
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
Could it be circular structure to JSON error? I suppose that as I cannot see your query function.
Can you also try
console.log(JSON.stringify(err)) //works ?
If you got error of // ⛔️ TypeError: Converting circular structure to JSON then it is the circular structure issue, that blocks you just "send" as you cannot send a circular object.
For still wanting to send circular object, refer to: https://github.com/WebReflection/flatted#flatted

How to make NodeJS carry on even if an error occurs?

I am building a simple login/register app. I am testing the login part. Whenever I input a wrong login, however, the backend (written in NodeJS and Express) crashes and stops.
Previously my code threw an error whenever the SQL returned error like so:
con.query("SELECT * FROM table_name WHERE username=" + usernameGiven, function(er, result) {
if (er) throw er;
return result;
}
This worked but had the issue as told above. So I removed the throw er part and replaced it with console.log(er) but still the nodeJS would stop and further login attempt will throw a CORS error.
So how can I stop it from doing and make it just log it and continue to the next request?
Edit:
I tried try and catch as shown below:
try {
con.query(sql_query, function(er, result) {
if (er) {
console.log(er);
}
response.json(result);
})
} catch (er) {
console.log(er);
}
However this still shows an error:
/home/x/CodeOver/LoginForm/api/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'password' of undefined
at Query.<anonymous> (/home/x/CodeOver/LoginForm/api/api.js:43:37)
at Query.<anonymous> (/home/x/CodeOver/LoginForm/api/node_modules/mysql/lib/Connection.js:526:10)
I'd suggest a little refactoring to make the code more robust to this type of failure.
The try .. catch blocks won't actually catch query errors in this situation, though I'll leave them there in case of any other error.
We should also use parameters here when querying. SQL Injection attacks are bad news and using parameters will also make the query less likely to result in a syntax error.
I'd also fail early and throw back a 400 error if our usernameGiven is not present.
Here is the updated code, I hope this helps you!
try {
if (!usernameGiven) {
response.status(400).send("Bad Request");
return;
}
let sql_query = "select * from table_name where username = ?";
con.query(sql_query, [usernameGiven], function(er, result) {
if (er) {
console.error("Error occurred:", er);
response.status(500).send("Internal Server Error")
} else {
response.json(result);
}
})
} catch (er) {
console.error("Error occurred:", er);
}

Can't catch exception from fs.createWriteStream()

In the main process of my Electron app, I'm trying to handle an exception thrown when creating a file that already exists. However, my catch clause is never entered, and the exception is spammed to the user. What am I doing wrong?
let file;
try {
// this line throws *uncaught* exception if file exists - why???
file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
}
catch (err) {
// never gets here - why???
}
The correct way to handle this case is by listening to the error event:
const file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
file.on('error', function(err) {
console.log(err);
file.end();
});
What I've found is:
https://github.com/electron/electron/issues/2479
I tried to replicate with pure Node.js, and it catches errors with process.on('uncaughtException', callback)
let desiredPath = '/mnt/c/hello.txt';
let fs = require('fs');
process.on('uncaughtException', function (error) {
console.log('hello1');
});
try {
fs.createWriteStream(desiredPath, {
flags: 'wx',
});
}
catch (err) {
console.log('hello');
}
//Output is: 'hello1'
I tried it with Ubuntu shell on Windows 10, in my case I don't have permissions to read that file and process.on('uncaughtException', callback) catches it correctly.

Grab events from Eventbrite API with Nodejs

So I'm unable to find any examples and the example used on the npm package README throws me an error.
So I'm using https://github.com/Datahero/node-eventbrite
I require it in app.js. I create the token variable and place my token in there.
I add this piece of snippet in
try {
var api = eventbriteAPI({
token: eventbrite_token,
version : 'v3'
});
} catch (error) {
console.log(error.message); // the options are missing, this function throws an error.
}
So on the README file it says the next line of code should be something like (replacing the user_id: with my user id).
api.owned_events({ user_id: 30 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
I get the error TypeError: api.owned_events is not a function
Basically I'm trying to get a list of events based on the location from the Eventbrite API via node. But I'm unable to even query from node and get what I want back. Has anyone any resources or can offer help?
Thank you!
I think there is an error on the README file, api should be declared outside the try/catch block:
var api;
try {
api = eventbriteAPI({
token: eventbrite_token,
version : 'v3'
});
} catch (error) {
console.log(error.message);
}
api.owned_events({ user_id: 30 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});

Trapping AssertionError in nested callback function

I am writing an updated testing library for Node.js and am trying to properly trap errors that occur in test callbacks
for some reason, the following code doesn't trap an AssertionError:
process.on('uncaughtException',function(err){
console.error(err); //an instance of AssertionError will show up here
});
[file1,file2,file2].forEach(function (file) {
self.it('[test] ' + path.basename(file), {
parallel:true
},function testCallback(done) {
var jsonDataForEnrichment = require(file);
request({
url: serverEndpoint,
json: true,
body: jsonDataForEnrichment,
method: 'POST'
}, function (error, response, body) {
if (error) {
done(error);
}
else {
assert(response.statusCode == 201, "Error: Response Code"); //this throws an error, which is OK of course
done();
}
});
});
});
I handle the callback (I named it "testCallback" above), with this code:
try {
if (!inDebugMode) {
var err = new Error('timed out - ' + test.cb);
var timer = setTimeout(function () {
test.timedOut = true;
cb(err);
}, 5000);
}
test.cb.apply({
data: test.data,
desc: test.desc,
testId: test.testId
}, [function (err) { //this anonymous function is passed as the done functon
cb(err);
}]);
}
catch (err) { //assertion error is not caught here
console.log(err.stack);
cb(err);
}
I assume the problem is that callbacks that result from async functions like those made in the request module, cannot be trapped by simple error handling.
What is the best way to trap that error?
Should I just flesh out the process.on('uncaughtException') handler? Or is there a better way?
The best way to handle this appears to be Node.js domains, a core module
https://nodejs.org/api/domain.html
it will likely be deprecated soon, but hopefully there will be a replacement that can have similar functionality, because the domain module is saving my ass right now, as I have no other way to trap errors, because the errors might be generated by my users' code, not my code.

Categories