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)
}
Related
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 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.
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.
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.
I'm developing a website with server-side JScript engine over ASP server.
I have several try-catch clauses in my code looking roughly like this:
try {
// do something
}
catch (err) {
// pass it to the frontend code
die("Exception caught: " + err.description);
}
I would very much like to display the line number in which the error occurred. The filename would be a nice bonus but it's not very important.
How can it be done?
Thanks!
The err object (of type ASPError) has Line and File properties - just what you need (see this for more properties).