I'm trying to run a sample code from Github to insert the data in fire store database but I am getting an error.
Here is the error:
21:1 error Expected catch() or return promise/catch-or-return
21:35 error Each then() should return a value or throw promise/always-return a value or throw
Here is the code where I am getting the error:
// getting data
db.collection('cafes').get().then((snapshot) => { //----line 21
snapshot.docs.forEach(doc => {
renderCafe(doc);
})
});
Those look like lint warnings, not actual JS errors unless you're running this in some non-standard environment.
The first one appears to be telling you that you have no .catch() to handle errors from your db .get(). That's good advice. You must handle errors.
The second one appears to be wrong. There's no rule that you have to return a value from a .then(). If it's the end of the chain and you're done with the processing, there's no reason to return anything. You can probably make the second warning go away by putting a return 0 after renderCafe(doc), though personally I'd either stop using a tool that gives such bad advice or configure it not to warn on this issue because it's wrong and adding dummy, non-functional code just to make some tool be happy is not something I recommend.
Related
I'm a JS game dev who's been trying to combat tampermonkey scripts for a while now.
I came up with a solution for people hooking into WebSockets where I'd cause the WebSocket to throw an error new WebSocket(0); (0 throws an error due to it being a number)
let output;
try {
output = new target(...args);
} catch(e) {
let source = e.stack.substring(e.stack.indexOf("("), 1 + e.stack.indexOf(")"));
e.stack = e.stack.replace(source, "nothing to see here");
throw e;
}
this code made the error's stack have all the information I was looking for replaced!
I've been looking at Object.defineProperty, and I was wondering how I could stop an error's stack from being modified before I have access to that specific error. And if anyone has any other ways I could stop a script from being loaded or run, I'd love to hear them!
One thing you could do is Object.freeze the error before throwing it. This would prevent people from altering the object's contents.
So for example:
try {
new WebSocket(0);
} catch (wsErr) {
throw Object.freeze(wsErr);
}
The code catching your error and trying to alter it would fail to be able to alter it. This should work as it will cause the code that was altering the error to throw with the following:
Cannot assign to read only property 'stack' of object ''
The other thing you'll have to consider is that in your code where you're catching the error, you will not be able to alter its contents either. Typically with errors, that's not a huge deal though. Tampering with errors is one of the only reasons I can think of for modifying the error.
I have a nodeJS application (server) and using some 3rd party npm modules.
Also in my application, I have the following code:
process.on("unhandledRejection", (reason, promise) => {
console.error(`Unhandled Rejection at: ${promise} reason: ${reason}`);
restartApp(); // ← Is this a must action?
});
Seems like not all the promises are rejected properly, in the 3rd party modules and maybe also in my code.
I know it's the last resource to use this event handler.
Question after catching this unhandle rejection event, do I need to restart my application?
It's useful to divide errors into two broad categories: Operational and Programmer errors.
Operational errors are (unavoidable) run-time problems experienced by correctly-written programs, such as disk full, network connection loss etc.
Programmer errors are caused by bugs or oversights in code, that can not be handled since they will cause the program to enter an unknown state, they could be in your code or a module you're calling.
Best practice for programmer errors is to crash immediately. You should run your programs using a restarter (see below) that will automatically restart the program in the event of a crash. With a restarter in place, crashing is the fastest way to restore reliable service in the face of a transient programmer error.
If the error is an operational error, it may make sense to try to recover or re-try the operation (if this makes sense). There's no point retrying a REST request if you're getting 400 errors for example, but there might be if you're getting 500 errors (the system may recover).
See more here in this very useful guide:
https://www.joyent.com/node-js/production/design/errors
In your specific case, you're handling an unhandledRejection, this means that an application is in an undefined state... very similar to an unhandledException, the best thing to do is clean up anything that needs to be done and then exit or restart, also log the error (this is super important!, is the error happening every day, hour or minute?)
I'd suggest using a process monitor such as PM2 or Forever. These can auto-restart when you exit due to an error, and do lots of other cool stuff like logging these events.
Here's another nice guide from Heroku on the same topic:
https://blog.heroku.com/best-practices-nodejs-errors
The blogger (Julián Duque) has even put together some best practice on handling these events:
https://blog.heroku.com/best-practices-nodejs-errors#putting-it-all-together
This looks a little like so:
const http = require('http')
const terminate = require('./terminate')
const server = http.createServer(...)
const exitHandler = terminate(server, {
coredump: false,
timeout: 500
})
process.on('uncaughtException', exitHandler(1, 'Unexpected Error'))
process.on('unhandledRejection', exitHandler(1, 'Unhandled Promise'))
process.on('SIGTERM', exitHandler(0, 'SIGTERM'))
process.on('SIGINT', exitHandler(0, 'SIGINT'))
The Terminate module:
function terminate (server, options = { coredump: false, timeout: 500 }) {
// Exit function
const exit = code => {
options.coredump ? process.abort() : process.exit(code)
}
return (code, reason) => (err, promise) => {
if (err && err instanceof Error) {
// Log error information, use a proper logging library here :)
console.log(err.message, err.stack)
}
// Attempt a graceful shutdown
server.close(exit)
setTimeout(exit, options.timeout).unref()
}
}
module.exports = terminate
I think this style of managed, centralized handling of these events is the right way to go.
I'm having a couple of really weird issues with JS, I don't know if they are related but they both look like coming from a same code execution strangeness:
This is the first one, which almost got me mad since I could't find any explanation for why it was happening and had to totally rewrite the code to make this issue disappear, inside an express app:
exports.someMiddleware(req, res) {
var something = req.somethingFromPastMiddleware
something = doSomeComputation(something) //all synchronous
console.log(something, something.someProp) //everything ok
if(something.someProp) {
//here is where I must throw the error
console.log(something, something.someProp) //undefined; error, cannot read someProp of undefined (wtf?????)
something.otherProp = doSomeOtherComputation(something) //all synchronous
}
console.log(something, something.someProp) //everything ok
res.status(200).json(something) //I get the response, without something.otherProp
}
the only times I got something.otherProp in the response was when I purposely created an error inside the if(something.someProp) code block, like referencing an undeclared variable and catching catching it
and now the second one, inside a react web app we have a promise chain:
api.dataConfirm(
this.refs.code.value()
).then(() => {
data.refresh();
).then(() => {
this.returnToApp();
}).catch(err => {
console.error(err)
})
this code runs fine everywhere, except for the iOS webview on iOS 9.x running on an actual iPhone (iPods ok, iPads ok, emulator ok)
on the physical iPhone data.refresh() gets called and returns the promise but don't actually do anything, also here making JS to throw an error on purpose, catching it and then going further makes the code run in the normal way
refresh() {
return api.dataStatus()
.then(res => {
//here is where I must throw the error
this.cache(res.body.data);
});
}
I cannot really tell what's going on, maybe some code execution optimization that in some particular cases does this stuff and interrupting execution with an error and then resuming it makes things work fine... guesses?
PS: Another thing that make it work is doing some random coding before the lines that get jumped, like creating vars, summing numbers, etc... but the error thing it's the only one that works for sure
Is there a way to handle all JavaScript errors and exceptions in ExtJS application globally and route it to a function that alerts the user on a server error?
window:onerror() doesn't seem to handle all the JavaScript errors, hence looking for some kind of catch in the code, to wrap it in to a more generic exception so that it would be caught?
See
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Error-static-method-handle
Globally handle any Ext errors that may be raised, optionally
providing custom logic to handle different errors individually. Return
true from the function to bypass throwing the error to the browser,
otherwise the error will be thrown and execution will halt.
Example usage:
Ext.Error.handle = function(err) {
if (err.someProperty == 'NotReallyAnError') {
// maybe log something to the application here if applicable
return true;
}
// any non-true return value (including none) will cause the error to be thrown
}
Normally an error would get handled by onerror, but returning true in Ext.Error.handle prevents that.
Also look at http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Ajax-event-requestexception
UPDATE
[Rewriting question to focus on the problem I am trying to understand.]
Is there a means in JavaScript to throw Exceptions that notify the line number where the problem occurs? Similar to C#'s debugger, if an error is thrown on line 50 then I will be taken to line 50.
For example, according to MDN EvalError represents an error with eval(). So, let's say I have a function that uses eval(). I want to use a specific error that is representative of the problem at hand, EvalError:
//As written here the error implies there is a problem on this line. See Firebug console window
var evalErra = new EvalError('required element missing from evaluation');
var stringFunc = "a=2;y=3;document.write(x*y);";
EvalString(stringFunc);
function EvalString(stringObject) {
//Some arbitrary check, for arguments sake let's say checking for 'x' makes this eval() valid.
if(stringObject.indexOf('x') !== -1) {
throw evalErra;
//throw 'required element missing from evaluation';//This way offers no line number
}
eval(stringFunc);//The problem really lies in the context of this function.
}
If I'm going about this all wrong, then please tell me how I should approach these kinds of issues.
When you throw an error, execution of the current code will stop and JS will work its way back up the execution tree until it finds a catch () which handles the particular type of error being thrown, or gets all the way up to the top of the tree, causing an "unhandled exception" error: You threw an error, and nothing caught it, and now someone's window got broken.
try {
if (true) {
throw 'yup'
}
} catch (e) { // catches all errors
... handle the error
}
When doing error handling you want to do the following
throw new Error("message");
Then if you ever handle this error look at err.stack (firefox/opera/chrome) or err.line (Safari) or err.IE_Y_U_NO_SHOW_ME_ERROR_LINE_NUMBER (IE) to find the line number.
If you want you can subclass Error.