Handling errors in server-side code

Knowing what happens at every time and how to fix it is key for development productivity. In backbeam while you are win the development environment backbeam you will see complete stack traces if errors are thrown. For example if you make some mistake writing JavaScript:

function runQuery() {
    backbeam.xselect('user').fetch(100, 0, response)
}

if (!backbeam.currentUser()) {
    runQuery()
} else {
    runOtherQuery()
}

You see the error message, the stack trace and the source code with all the lines in the stack of the error highlighted. So you can find quickly the reason of the error and the root cause.

Note that as you can see in the first example you can acces the err.name and the err.message separately. Examples of error names are: ObjectNotFound, FieldNotFound, EntityNotFound,...

But what happens when the error is not due to a Javascript syntax error? Well, all the asynchronous methods in backbeam have a first error parameter in the callback functions. If there is an error you can handle it. For example if you make a mistake in a BQL query...

backbeam.select('user').query('where name != ?', 'john').fetch(100, 0, function(err, objects) {
    if (err) return response.send(err.name+': '+err.message)
    response.send('Number of objects: '+objects.length)
})

There is an error in the BQL query (there is no != operator) so an error is passed to the callback and the if is evaluated and the following text is shown in the HTTP response:

SyntaxError: Expected " ", "<", "<=", "=", ">", ">=", "has", "in", "is not", "is", "like" or "not in" but "!" found.

If your controller is very complex maybe you have many BQL queries and this information is not enough to fix the error since you don't know the exact line that caused the error. And in this case the JavaScript error is not created in your code so the stack trace will be empty. But you can create an error and throw it yourself and you will get all the information like in the first example of this article. It is as simple as this:

backbeam.select('user').query('where name != ?', 'john').fetch(100, 0, function(err, objects) {
    if (err) throw new Error(err)
    response.send('Number of objects: '+objects.length)
})

This is the result in your browser screen

Finally, you must know that when you are in the production environment you won't see error messages or stack traces. Your users by default will see an Internal Error message but you can personalize it. Just create a template named 500.html and put anything you want. Remember, this only happens in the production environment :-)