I have a $.getJSON() call in my try that is throwing an error, but the catch is not being triggered. Nothing is happening. Just the error in the console.
Why is this?
What I'm trying to do is do something if the JSON is loaded and do something else if there is a failure or error in the request.
Here is my code:
try{
$.getJSON('https://www.googleapis.com/freebase/v1/search?query=&filter=(all+type%3A%22nominated%20works+exhibited_at%3A%222012%20grammy%27s%22)&indent=true', function(searchJSON){
alert('sucesss!');
});
}
catch(e){
alert('failure: '+e);
}
Here is a link to a jsfiddle: http://jsfiddle.net/sgeg56c3/
Your callback function is asynchronous, while your try / catch block is synchronous. By the time your async callback has finished, the try / catch block may have already finished.
Since exceptions are handled synchronously, you'll need to use a different method for error handling.
I recommend reading Asynchronous Error Handling in Javascript
Related
I to have write a function that checks if a file is valid (exists & granted correct permissions), and other one that returns a valid filepath. These functions call the check file function which uses try catch.
Should my function validFilePath catch errors also?
No, you do not need to use try/catch in all circumstances.
If there is no code path that causes the function you're calling to throw, then you don't need to surround it with a try/catch. It is your responsibility as a programmer to know what the functions you call can do in terms of errors and to code to that. Do they return an error? Do they return null? Do they throw an exception? If they do not throw an exception because they already catch any possible exception, then there is no reason for the caller to surround the function call with a try/catch.
You do need to code for all possible return values, including error conditions.
For example I just tried to catch ENOENT by naively doing this:
try {
res.sendFile(path);
} catch (e) {
if (e.code === 'ENOENT') {
res.send('placeholder');
} else { throw e; }
}
This doesn't work!
I know that the right way is to use the error callback of sendFile, but it's really surprising and bad for me that the fundamental language feature of exceptions doesn't work here.
I guess maybe express itself is doing the catching. And they want to not have the errors kill the server so quickly. It's understandable.
But I just get this lame message:
Error: ENOENT: no such file or directory, stat '<file>'
at Error (native)
Not great.
Due to documentation res.sendFile is async function, so try/catch won't work in this case. If you want to handle res.sendFile result you must pass callback as last argument.
res.sendFile(path, function (e) {
if (e) {
if (e.code === 'ENOENT') {
res.send('placeholder');
} else {
throw e;
}
}
});
Its because of the Asynchronous nature of Javascript that the code will not catch the exception you are throwing. The res.sendFile is executed outside the scope of try block and the try block execution will be over after the call to res.sendFile method.
That is the reason why it is always advised to use the callback mechanism with err object as the first argument to the callback and you can check that first before proceeding
res.sendFile(path, function (e) {
// check the error first
// then procedd with the execution
});
Generally speaking, you want to avoid using exceptions to control program flow.
Also, since you're apparently programming this in Node.js, you pass a callback function to keep Node running asynchronously. Node.js is not multithreaded, because JavaScript is not multithreaded, so it cannot have more than one thing going on at a time. That means that if your code is hung up handling an exception, nothing else is happening. And Exceptions are expensive. Doing expensive cleanup in a single-threaded server-side application will harm performance and scalability. Nor is JavaScript itself magically asynchronous. It's asynchronous only if you use callback functions to loosen it up.
So when you pass a callback function to res.send, that function gets called asynchronously when the res.send function finishes (or exits without finishing due to an error), without the overhead of a thrown exception. Thus, if you want to handle errors, passing a callback method is the way to do it.
I have a basic understanding of javascript and have been learning how asynchronous functions work in node.js. I've been very confused by callback functions with the parameter error. For example, here's some code:
contact.saveContacts = function(contactArray, done) {
var jsonfile = require('jsonfile')
jsonfile.writeFile('data.json', contactArray, done)
}
Contact.saveContacts(contacts, function(err) {
console.log('success')
}
My question is, why does the callback function contain the parameter error? I'm confused to why it's there because it seems as if it serves no purpose in the function it calls.
This is a pattern called an error first callback and is used a lot in javascript.
See this article for reference.
Typically synchronous functions either return successfully, possibly with a value, or throw an exception if there is a problem. The calling code can choose what to do if an exception is thrown, by either catching and inspecting the error or by letting it fall through to other code that may handle the error.
Asynchronous callback functions are called after the calling code has already executed. This means there's no opportunity to catch thrown exceptions. So instead of throwing, errors are passed through to the callback function so the calling code can handle both success and error states.
in case there is a problem with write operation such as permissions error object is invoked and the reason in this to prevent unexpected errors.
Imagine we are giving a order to do computer starts doing it but on the way theres a block about permissions that computer cannot write into that dir in this case computer doesnt know what to do and our program crashes to prevent this inside callback we specify what to do in such cases for example if permission is denied and the reason is write permission prompt user for password and force writing or open a box to user that user must run this as user
The error parameter has no usage if everything goes fine. But, its too useful when there comes an error. Any type of error e.g. runtime error, of file has been deleted or anything, if happens, the details of the error will be present in the error parameter of the callback. So, its better to use that parameter as following:
Contact.saveContacts(contacts, function(err) {
if(err){
console.log(err);
}
else{
console.log('success');
}
}
In this way, you will get to know any error, if that happens with the function.
In test complete I am trying to use a try-catch block to see if a message box has an okay button and then click the okay button without crashing. I put the click operation inside a try block so if it fails the catch block can deal with the error, but it is crashing inside the try block. Here's an example:
try
{
okayButton = SomeLocation;
okayButton.click();
}
catch(err)
{
do something;
}
I would think that when Test Complete can't click the okay button, it would move into the catch block. However, I get an error on the okayButton.click(); line, which stops the test run. It says "there was an attempt to preform an action on a zero-sized window.". Does anyone know how do deal with this? Thanks in advance.
If okayButton.click(); does not throw an err, Your catch block will never be executed. You should validate that when okayButton.click(); fails, it throws the error your catch block is expecting.
It may be that okayButton.click(); is returning the error instead of throwing it.
I encountered quite annoying problem. I can't catch errors thrown from within the functions. And to be honest - I wouldn't care much if not the fact that the same applies for throwing errors from within the JavaScript Objects.
Here's the sample code:
http://jsfiddle.net/TxsHK/1/ (you'll need firebug console to test this code)
function ViewError($CONTENT){
this.content = $CONTENT;
return this.content;
};
try{
$(document).ready(function() {
//--------------
throw ViewError('Test error');
//--------------
});//$(document).ready(function() {
}catch (e) {
if (e instanceof ViewError) {
console.info(e.message);
}
else{
console.warn(e.message);
}
}
gives an error
TypeError: e is undefined
Why? The errors thrown by functions (or objects) should be perfectly catchable. That's the whole purpose of try - catch block: to catch exceptions out of functions. At least... so it is in other languages.
Anyone can explain what's going on? And how can I catch exceptions from within the functions / objects?
Your "ViewError" function doesn't return anything. You're therefore throwing undefined. (edit — your fiddle is diffferent from the posted code - don't do that!)
The "ViewError" function is being called in a way that I don't think to be correct, given the way the code is written. I think you want throw new ViewError("Test error"); in order to make sure a new object is created.
There's another problem: you're expecting that you'll be able to catch exceptions thrown from that call to $(document).ready(), but that's not necessarily going to work. If the document isn't ready yet when that code runs, then you'll get no exceptions because the call returns immediately. The function you pass in would be called later, when the document is ready.