How do I listen to an uncaught exception error in meteor?
The errors are of course specific to the cause, so please can you provide a pseudo style code/explanation that states the concept of handling this error.
An example use case:
A user clicks 'logout' but there is an uncaught exception and the user does not get logged out and so the connection to the server remains open.
You can use the callbacks, they usually provide a reason parameter. E.g
Meteor.call("some_random_non_existent_method", function(err, result) {
if(err) return alert(err.reason)
});
Most meteor callbacks have a error param. With the logout its Meteor.logout(function(err) { ... })
You should be able to catch most types of errors like this. If you want to capture all errors you can use try..catch. Everything in the try block will try to run until it throws an error. You can catch this and provide feedback to the user.
try {
//This will throw an error
this.run_something.go_make_error()
}catch(e) {
alert("There was an error running this");
}
Related
From backend I am getting specific error message during the post request. How may I get this message in javascript?
catch(err => console.log('error', err.response.data))
With this code I am getting just the type of the error, but I need the message which I throw from backend. F.ex throw ConflictException("The name is already exist"). I need get the following message "The name is already exist", not just the the type.
<!DOCTYPE html>
<html>
<body>
<script>
try {
throw new Error('Custom Exception');
}
catch(err) {
if(err.message){
console.log('inside if & error message as follow : ',err.message);
}else {
console.log('inside else');
console.log(err);
}
}
</script>
</body>
</html>
Above is for demonstration purpose, if it still not working then try
catch(err => console.log('error', err?.message));
Caught errors generally have a message field stored at error?.message or if you using things like Axios or other API requests, error messages are generally at error.response?.data?.message!
Note: ?. is an optional chaining to prevent other errors like Can not read properties of undefined, reading x
I'm using postgres with knex javascript library to build my sql queries. I want to handle all thrown errors from postgres server, so the way I want to do this is by checking the type of the thrown error.
try {
// knex query here
} catch(error) {
if(error instanceof DatabaseError) {
// handle pg error by checking error.code or something else
// then send an custom error message to the client
}
// handle another error here which is not caused by the postgres server
}
Is there any way to handle the error like this ?
Catching Knex/DB Errors:
You can use the async/await syntax:
async function() {
try {
await knex(/* knex query here*/)
} catch(error) {
if(error instanceof DatabaseError) {
// handle pg error by checking error.code or something else
// then send an custom error message to the client
}Sorry
// handle another error here which is not caused by the postgres server
}
If for some reason you don't want to use that (newer) syntax, you can also chain a .catch ...
knex(/* knex query here*/)
.then(doWhatever)
.catch(error => {
if(error instanceof DatabaseError) { // ...
});
Alternative you can also use Knex's query-error (https://knexjs.org/#Interfaces-query-error) ... but personally I've never seen the point when the built-in promise handlers work just fine.
(EDIT) Distinguishing PG Errors From Knex Ones:
If you want to differentiate Knex and PG-specific errors, you can hook up an error-handler to your PG connection directly (bypassing Knex) like so:
function afterCreate(connection, callback) {
connection.on("error", connectionError);
callback(null, connection);
}
db.client.pool.config.afterCreate = afterCreate;
If you do that you won't need a error instanceof DatabaseError, because all errors caught by the connection.on will be PG errors.
You might also find this issue thread (where I got that code from) useful: https://github.com/knex/knex/issues/522, as it features a discussion of error handling in Knex, and specifically handling of underlying DB errors.
(EDIT) But How Can I Distinguish Errors When I Catch Them?
Unfortunately I don't think PG errors don't have a unique prototype (ie. class) or other distinguishing feature. You can see this by looking at an example one (from that thread I linked):
{"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":5432}
As you can see, there's no way to look that and know "that's coming from PostgreSQL", unless you start checking for specific features like code === 'ECONNREFUSED' (there is no isPg: true flag on the error).
And why doesn't Knex just intelligently identify DB errors for us? From that same issue thread:
It is pretty much impossible to create events like redis have for knex because of multitude of different db drivers which doesn't actually support listening for connection errors
-elhigu (Knex team member)
Occasionally, when I run my puppeteer script, I’ll get a “page crashed” error. It’s most likely not a software error, but something to do with the proxy IPs I’m using/webpages I’m scraping. So all I’m really looking to do is just catch the error, close the current page, and open up a new page.
However, my try catch block doesn’t seem to be working. My code is structured like this:
try {
//puppeteer code
}
catch(e) {
console.log(‘caught error ‘ + e);
}
But when the page crashed error happens, I see “unhandled promise rejection error” instead of my console.log message. What’s going on here?
From here:
page.on('error', msg => {
console.error(...);
throw msg ;
});
And this is also advised to globally catch all uncaught errors in your code:
process.on('unhandledRejection', error => {
console.error(...);
throw error;
});
I want to catch a firestore error and execute code based on what kind of error it is. (My database is build that if a document doesn't exist you won't be able to access it and therefore I have been getting a lot of permission-denied errors for non-existent documents. My solution is to check the error and create a document if I get a permission denied error.)
This is my current code:
userDataDocRef.collection('emailPreferences').doc('main').get().then(function(doc) {
if (doc.exists) {
var data = doc.data();
console.log(data);
var getGameUpdates = data.getGameUpdates;
switchEmailNewGames.checked = getGameUpdates;
} else {
}
}).catch(function(error) {
console.log(error)
if (error == firebase.firestore.FirestoreError.permission-denied) {
console.log('FIREBASE PERMISSION DENIED ERROR')
}
})
My Question: How do I check what kind of error I got properly? (what I have at the moment doesn't work)
Thank you for your help!
There is no way to determine from the response what specific security rule failed. This is by design, since exposing this information would give malicious users access to important information about how your database is secured. That's why the error message sent to the client is always a generic "permission denied".
In general depending on error message like this for regular flow control sounds like an antipattern. If you only want to create a document if it doesn't exist, perform the check in a transaction, which ensures the check and create happen atomically.
Well, after reading some things about this issue, i decide to ask about.
The idea is simple in the core: detect incoming invalid URL's/URI's and return a response to the client with the pertinent code/data.
Normally, when treat the errors in node, we use syntax like:
if (err) {
return res.status(500).json(error: {msg: err.message, stack: err.stack});
}
Okay, that is pretty simple but the essential thing is that we detect: "hey, if an error occurs, shoot this thing to the client".
But what if it's not an 500 internal? As i know, bad request errors are send like a client error and have their own stack, type and message in the prompt, rigth?
Reading This, i found the URIError constructor, that points to an instance representing an error that occurs with ivalids URI's. So, it's possible to make some like this:
if (err instanceof URIError) { /* send a handler for bad request */ };
Or i need to validate from scratch the URI and make my own error inheritance?
Any hint? Idea? ... Thanks in advance! <3
I usually do this by defining the routes I want:
app.get('/good' ... );
app.post('/alsogood' ... );
And then to catch unrouted urls, do:
app.all('*', function(req, res) {
throw new Error("Bad request")
})
And then inject an error handling middleware:
app.use(function(e, req, res, next) {
if (e.message === "Bad request") {
res.status(400).json({error: {msg: e.message, stack: e.stack}});
}
});
You can obviously get a lot more complex than this, but this simple idea gets the point across.
Also, for what it's worth, you should probably throw a 404 back to to the client if they're trying to access a URL that doesn't exist.