Customize the 404 and 401 pages
When Total.js cannot serve a request it shows a built-in error page. A route whose URL is # plus the status code replaces it: ROUTE('#404', fn) for "not found", ROUTE('#401', fn) for "not authorized", and the same for #400, #431 and others. The handler receives $ like any route, but you set the status yourself with $.response.status: Total.js does not do it for you when a custom handler exists. Without a custom handler the built-in page is used and AJAX requests (header x-requested-with) get a JSON error instead of HTML.
$.fallback(code) sends the current request to the handler for code, which is how you answer 404 for a record that does not exist or 403 for a forbidden resource from inside your own code.
exports.install = function() {
ROUTE('#404', not_found);
ROUTE('#401', unauthorized);
ROUTE('GET /items/{id}/', item);
ROUTE('+GET /private/', private_page);
};
var items = { '1': 'First item' };
function item($) {
var name = items[$.params.id];
if (name)
$.json({ name: name });
else
$.fallback(404);
}
function private_page($) {
$.plain('secret');
}
function not_found($) {
$.response.status = 404;
$.html('<h1>Nothing here</h1><p>' + $.url.encode() + ' does not exist.</p>');
}
function unauthorized($) {
$.response.status = 401;
$.json({ error: 'Please sign in first' });
}
AUTH(function($) {
$.invalid();
});