update history.md for acceptParams change (#6177)
[express.git] / examples / error / index.js
blobd733a81172d0e12c89fb5fc4e9c087684aaf3458
1 'use strict'
3 /**
4 * Module dependencies.
5 */
7 var express = require('../../');
8 var logger = require('morgan');
9 var app = module.exports = express();
10 var test = app.get('env') === 'test'
12 if (!test) app.use(logger('dev'));
14 // error handling middleware have an arity of 4
15 // instead of the typical (req, res, next),
16 // otherwise they behave exactly like regular
17 // middleware, you may have several of them,
18 // in different orders etc.
20 function error(err, req, res, next) {
21 // log it
22 if (!test) console.error(err.stack);
24 // respond with 500 "Internal Server Error".
25 res.status(500);
26 res.send('Internal Server Error');
29 app.get('/', function () {
30 // Caught and passed down to the errorHandler middleware
31 throw new Error('something broke!');
32 });
34 app.get('/next', function(req, res, next){
35 // We can also pass exceptions to next()
36 // The reason for process.nextTick() is to show that
37 // next() can be called inside an async operation,
38 // in real life it can be a DB read or HTTP request.
39 process.nextTick(function(){
40 next(new Error('oh no!'));
41 });
42 });
44 // the error handler is placed after routes
45 // if it were above it would not receive errors
46 // from app.get() etc
47 app.use(error);
49 /* istanbul ignore next */
50 if (!module.parent) {
51 app.listen(3000);
52 console.log('Express started on port 3000');