SHOW:
|
|
- or go back to the newest paste.
| 1 | //* | |
| 2 | //* GOAL: HAVE GLOBAL Error HANDLER CATCH Error THROWN IN CALLBACK FROM POSTGRES .QUERY | |
| 3 | //* | |
| 4 | ||
| 5 | var express = require('express')
| |
| 6 | var app = module.exports = express.createServer(); | |
| 7 | ||
| 8 | // Configuration | |
| 9 | app.configure(function() {
| |
| 10 | app.use(app.router); | |
| 11 | ||
| 12 | //*********************************************** | |
| 13 | //* | |
| 14 | //* Global Error handler. Catches error from /throw1 but not from /throw2 | |
| 15 | //* | |
| 16 | //*********************************************** | |
| 17 | app.use(function(err, req, res, next) {
| |
| 18 | console.log("In global Error handler. Error was:");
| |
| 19 | console.log(err); | |
| 20 | res.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"><html><head><title>Handler</title></head><body>" + err + "</body></html>");
| |
| 21 | res.end(); | |
| 22 | }); | |
| 23 | ||
| 24 | }); | |
| 25 | ||
| 26 | app.use(express.errorHandler({
| |
| 27 | dumpExceptions: true, | |
| 28 | showStack: true | |
| 29 | })); | |
| 30 | ||
| 31 | app.get("/throw1",
| |
| 32 | function() {
| |
| 33 | throw new Error("thrown in /throw1");
| |
| 34 | }); | |
| 35 | ||
| 36 | app.get("/throw2",
| |
| 37 | function(req, res, next) {
| |
| 38 | var conString = process.env.DATABASE_URL; | |
| 39 | // on heroku and on my local dev box | |
| 40 | var client = new require('pg').Client(conString);
| |
| 41 | client.connect(); | |
| 42 | ||
| 43 | client.query({
| |
| 44 | text: "INSERT INTO acct(email,password) values($1, $2)", | |
| 45 | values: ["foo", "bar"] | |
| 46 | }, | |
| 47 | function(err, result) {
| |
| 48 | //*********************************************** | |
| 49 | //* | |
| 50 | //* if Error thrown here it is NOT caught by the global error handler set with app.use in app.js. | |
| 51 | //* | |
| 52 | //*********************************************** | |
| 53 | ||
| 54 | // If you can help it, do this. | |
| 55 | - | throw ("thrown in /throw2");
|
| 55 | + | next("callback style error in /throw2");
|
| 56 | return; | |
| 57 | ||
| 58 | ||
| 59 | // If it is external code, wrap it and call next. | |
| 60 | try {
| |
| 61 | throw ("thrown in /throw2");
| |
| 62 | catch (error) {
| |
| 63 | next(error); | |
| 64 | } | |
| 65 | }); | |
| 66 | ||
| 67 | }); | |
| 68 | ||
| 69 | app.get("/nop",
| |
| 70 | function(req, res) {
| |
| 71 | res.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"><html><head><title>NOP</title></head><body>NOP</body></html>");
| |
| 72 | res.end(); | |
| 73 | }); | |
| 74 | ||
| 75 | app.listen(3000, | |
| 76 | function() {
| |
| 77 | console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
| |
| 78 | }); |