You don't have to use try..catch
unless the operation uses synchronous code (such as making a request using http.get
using the meteor http package).
The error code is generally returned by the other server. 200 means its ok. There is a huge list of potential error codes and what they mean.
So the status code will be returned by the callback in the error
object but wont be caught by the catch
unless its thrown using throw
like you've mentioned.
In javascript the problem is when there are callbacks with the error parameter it doesn't actually throw an error that can be caught from where the original function is fired (the request()
method you have) if that makes sense.
Even if you use throw
in the callback it wont be caught by catch
. This is because the callback is fired as an entirely new event. If you want to use the catch
technique you need synchronous javascript. I.e with the http package.
meteor add http
Then the code:
try {
var result = HTTP.get("<url>")
result.content //this will contain the response
}catch(e) {
the `e` object will contain the error (if the status code is not 200)
}
You can change the error by throwing your own inside the catch(e) {...}
block i.e
...
catch(e) {
throw new Meteor.Error(500, "Internal Server Error");
}
...
You can throw either a new Error
or a new Meteor.Error
. The difference being that Meteor.Error will send the error down to the client too as part of the err
callback if the piece of code is being run in a method called from the client using Meteor.call
e.g
Meteor.call("something", function(err, result) {
if(err) alert(err.reason);
});
If this calls a method like this:
Meteor.methods({
something: function() {
throw new Meteor.Error(500, "This is the message");
}
});
The client will show a message box saying This is the message
as the err.reason
. If you throw new Error(..
it will not send the message down to the client and instead the message will be Internal Server Error
instead of This is the message
In the method you could have the code that requests the url. If it throws an error within it it would bubble up the stack and find its way to the client.