Skip to content

Instantly share code, notes, and snippets.

@alanhoff
Created July 3, 2014 00:18
Show Gist options
  • Select an option

  • Save alanhoff/f13429d819df44d9a323 to your computer and use it in GitHub Desktop.

Select an option

Save alanhoff/f13429d819df44d9a323 to your computer and use it in GitHub Desktop.
var express = require('express');
var domain = require('domain');
var bodyParser = require('body-parser');
var app = express();
// Esse middleware precisa vir antes de tudo, aqui está a mágica
// o domain é responsável por escutar por erros, se algum erro
// acontecer, ele vai automaticamente chamar o next() com um
// erro, e disparar a última rota cadastrada
app.use(function(req, res, next){
var d = domain.create();
d.add(req);
d.add(req);
d.on('error', next);
d.run(next);
});
app.get('/sintaxe', function(req, res, next){
// Forçamos um erro de sintaxe. HueHueHue não existe
var error = new HueHueHue('Ocorreu um erro?');
});
app.post('/json', bodyParser.json(), function(req, res){
// Provelmente não vai chegar aqui se
// vc enviar um json errado
res.json({ok : true});
});
app.get('/async', bodyParser.json(), function(){
// Ele também pega erros assíncronos
setTimeout(function(){
// res.jso não existe
res.jso({ok : true});
}, 1000);
});
// Isso deve vir no final
// Middleware para páginas não encontradas
app.use(function(req, res, next){
next(new Error('Página não encontrada'));
// Também pode terminar a requisição
// com um html bunitinho em vez de chamar
// o next
});
// Última rota na app que tem 4 parâmentros,
// logo ela é responsável por tratar os erros
app.use(function(err, req, res, next){
console.log(err);
console.log(err.stack);
res.send('<h1>Oooops</h1><pre>' + err.stack + '</pre>');
});
app.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment