├── .gitignore ├── .jshintrc ├── README.md ├── app.js ├── bin └── www.js ├── engines ├── engine.js ├── httpHandler.js ├── readPostData.js └── render.js ├── package.json ├── routes ├── index.js ├── log.js ├── route.js └── script.js ├── scripts ├── asyncHandler.js ├── asyncHandlerDom.js ├── badHandler.js ├── badHandlerDom.js ├── error.js ├── errorAjaxHandlerDom.js ├── errorHandlerDom.js ├── properHandlerDom.js ├── specifiedError.js ├── uglyHandler.js ├── uglyHandlerDom.js └── uglyHandlerImproved.js ├── tests ├── engines │ ├── httpHandlerTest.js │ └── responseMock.js ├── routes │ ├── indexRequestTest.js │ ├── logRequestTest.js │ └── scriptRequestTest.js └── scripts │ ├── asyncHandlerTest.js │ ├── badHandlerTest.js │ ├── errorTest.js │ ├── uglyHandlerImprovedTest.js │ └── uglyHandlerTest.js └── views └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | 3 | node_modules 4 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "curly": true, 3 | "eqeqeq": true, 4 | "freeze": true, 5 | "futurehostile": true, 6 | "maxdepth": 3, 7 | "maxstatements": 20, 8 | "maxparams": 7, 9 | "funcscope": true, 10 | "esversion": 5, 11 | "forin": true, 12 | "latedef": true, 13 | "maxcomplexity": 15, 14 | "noarg": true, 15 | "nocomma": true, 16 | "nonbsp": true, 17 | "nonew": true, 18 | "undef": true, 19 | "unused": true, 20 | "singleGroups": true, 21 | "strict": "implied", 22 | "node": true, 23 | "browser": true, 24 | "mocha": true, 25 | "-W100": true 26 | } 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A Guide to Proper Error Handling in JavaScript 2 | 3 | Camilo Reyes explains the best practices for proper error handling in JavaScript, including how to deal with errors thrown by asynchronous code. 4 | 5 | ## Requirements 6 | 7 | * [Node.js](http://nodejs.org/) 8 | 9 | ## Installation Steps (if applicable) 10 | 11 | 1. Clone repo 12 | 2. Run `npm install` 13 | 3. Run `npm start` 14 | 4. Visit [http://localhost:1337/](http://localhost:1337/) 15 | 5. Run `npm test` to run unit tests 16 | 17 | ## License 18 | 19 | The MIT License (MIT) 20 | 21 | Copyright (c) 2016 SitePoint 22 | 23 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 24 | 25 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 26 | 27 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | var route = require('./routes/route'); 3 | 4 | var app = http.createServer(function (req, res) { 5 | route(req, res); 6 | }); 7 | 8 | module.exports = app; 9 | -------------------------------------------------------------------------------- /bin/www.js: -------------------------------------------------------------------------------- 1 | var app = require('../app'); 2 | var port = process.env.port || 1337; 3 | 4 | app.listen(port); 5 | console.log('Listening on http://localhost:' + port); 6 | -------------------------------------------------------------------------------- /engines/engine.js: -------------------------------------------------------------------------------- 1 | var render = require('./render'); 2 | var httpHandler = require('./httpHandler'); 3 | var readPostData = require('./readPostData'); 4 | 5 | module.exports = { 6 | render: render, 7 | httpHandler: httpHandler, 8 | readPostData: readPostData 9 | }; 10 | -------------------------------------------------------------------------------- /engines/httpHandler.js: -------------------------------------------------------------------------------- 1 | function httpHandler(err, res, content) { 2 | if (err) { 3 | res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }); 4 | res.end('Error: ' + err.message); 5 | } else { 6 | var headers = { 'Content-Type': content.type }; 7 | if (content.nocache) { 8 | headers['Cache-Control'] = 'no-cache'; 9 | } 10 | res.writeHead(200, headers); 11 | res.end(content.response); 12 | } 13 | } 14 | 15 | module.exports = httpHandler; 16 | -------------------------------------------------------------------------------- /engines/readPostData.js: -------------------------------------------------------------------------------- 1 | function readPostData(req, fn) { 2 | var body = ''; 3 | req.on('data', function (chunck) { 4 | body += chunck; 5 | }); 6 | req.on('end', function () { 7 | fn(body); 8 | }); 9 | } 10 | 11 | module.exports = readPostData; 12 | -------------------------------------------------------------------------------- /engines/render.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var path = require('path'); 3 | 4 | function render(req, res, fn) { 5 | var fullpath = path.join(__dirname, '../') + req.path; 6 | fs.readFile(fullpath, 'utf-8', function (err, text) { 7 | var content = { 8 | response: text, 9 | type: req.type, 10 | nocache: req.nocache 11 | }; 12 | fn(err, res, content); 13 | }); 14 | } 15 | 16 | module.exports = render; 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "propererrorhandlingjavascript", 3 | "version": "0.0.2", 4 | "private": true, 5 | "description": "Proper ErrorHandling in JavaScript", 6 | "author": { 7 | "name": "C R", 8 | "email": "reyesc@gmail.com" 9 | }, 10 | "scripts": { 11 | "start": "node bin/www.js", 12 | "test": "node node_modules/mocha/bin/_mocha tests/**/*.js" 13 | }, 14 | "devDependencies": { 15 | "mocha": "^3.4.2", 16 | "should": "^11.2.1", 17 | "supertest": "^3.0.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /routes/index.js: -------------------------------------------------------------------------------- 1 | var engine = require('../engines/engine'); 2 | 3 | var request = { 4 | path: 'views/index.html', 5 | type: 'text/html; charset=utf-8', 6 | nocache: true 7 | }; 8 | 9 | function getIndex(res) { 10 | engine.render(request, res, engine.httpHandler); 11 | } 12 | 13 | module.exports = getIndex; 14 | -------------------------------------------------------------------------------- /routes/log.js: -------------------------------------------------------------------------------- 1 | var engine = require('../engines/engine'); 2 | 3 | var content = { 4 | response: null, 5 | type: 'application/json; charset=utf-8', 6 | nocache: true 7 | }; 8 | 9 | function postLog(req, res) { 10 | if (req.method === 'POST' && req.url === '/log') { 11 | engine.readPostData(req, function (body) { 12 | if (body) { 13 | console.log(body); 14 | console.log(); 15 | } 16 | engine.httpHandler(null, res, content); 17 | }); 18 | return true; 19 | } 20 | return false; 21 | } 22 | 23 | module.exports = postLog; 24 | -------------------------------------------------------------------------------- /routes/route.js: -------------------------------------------------------------------------------- 1 | var index = require('./index'); 2 | var script = require('./script'); 3 | var log = require('./log'); 4 | 5 | function route(req, res) { 6 | if (log(req, res)) { 7 | } else if (script(req, res)) { 8 | } else { 9 | index(res); 10 | } 11 | } 12 | 13 | module.exports = route; 14 | -------------------------------------------------------------------------------- /routes/script.js: -------------------------------------------------------------------------------- 1 | var engine = require('../engines/engine'); 2 | 3 | function getScript(req, res) { 4 | if (req.method === 'GET' && req.url.indexOf('/scripts/') >= 0) { 5 | var request = { 6 | path: req.url.slice(1), 7 | type: 'application/javascript; charset=utf-8' 8 | }; 9 | engine.render(request, res, engine.httpHandler); 10 | return true; 11 | } 12 | return false; 13 | } 14 | 15 | module.exports = getScript; 16 | -------------------------------------------------------------------------------- /scripts/asyncHandler.js: -------------------------------------------------------------------------------- 1 | function asyncHandler(fn) { 2 | try { 3 | setTimeout(function () { 4 | fn(); 5 | }, 1); 6 | } catch (e) { } 7 | } 8 | 9 | if (typeof module === 'object') { 10 | module.exports = asyncHandler; 11 | } 12 | -------------------------------------------------------------------------------- /scripts/asyncHandlerDom.js: -------------------------------------------------------------------------------- 1 | (function (handler, bomb) { 2 | var asyncButton = document.getElementById('async'); 3 | 4 | if (asyncButton) { 5 | asyncButton.addEventListener('click', function () { 6 | handler(bomb); 7 | }); 8 | } 9 | }(asyncHandler, error)); 10 | -------------------------------------------------------------------------------- /scripts/badHandler.js: -------------------------------------------------------------------------------- 1 | function badHandler(fn) { 2 | try { 3 | return fn(); 4 | } catch (e) { } 5 | return null; 6 | } 7 | 8 | if (typeof module === 'object') { 9 | module.exports = badHandler; 10 | } 11 | -------------------------------------------------------------------------------- /scripts/badHandlerDom.js: -------------------------------------------------------------------------------- 1 | (function (handler, bomb) { 2 | var badButton = document.getElementById('bad'); 3 | 4 | if (badButton) { 5 | badButton.addEventListener('click', function () { 6 | handler(bomb); 7 | console.log('Imagine, getting promoted for hiding mistakes'); 8 | }); 9 | } 10 | }(badHandler, error)); 11 | -------------------------------------------------------------------------------- /scripts/error.js: -------------------------------------------------------------------------------- 1 | function error() { 2 | var foo = {}; 3 | return foo.bar(); 4 | } 5 | 6 | if (typeof module === 'object') { 7 | module.exports = error; 8 | } 9 | -------------------------------------------------------------------------------- /scripts/errorAjaxHandlerDom.js: -------------------------------------------------------------------------------- 1 | window.addEventListener('error', function (e) { 2 | var stack = e.error.stack; 3 | var message = e.error.toString(); 4 | 5 | if (stack) { 6 | message += '\n' + stack; 7 | } 8 | 9 | var xhr = new XMLHttpRequest(); 10 | xhr.open('POST', '/log', true); 11 | xhr.send(message); 12 | }); 13 | -------------------------------------------------------------------------------- /scripts/errorHandlerDom.js: -------------------------------------------------------------------------------- 1 | window.addEventListener('error', function (e) { 2 | var error = e.error; 3 | console.log(error); 4 | }); 5 | -------------------------------------------------------------------------------- /scripts/properHandlerDom.js: -------------------------------------------------------------------------------- 1 | (function (bomb) { 2 | var properButton = document.getElementById('proper'); 3 | 4 | if (properButton) { 5 | properButton.addEventListener('click', function () { 6 | bomb(); 7 | }); 8 | } 9 | }(error)); 10 | -------------------------------------------------------------------------------- /scripts/specifiedError.js: -------------------------------------------------------------------------------- 1 | var SpecifiedError = function SpecifiedError(message) { 2 | this.name = 'SpecifiedError'; 3 | this.message = message || ''; 4 | this.stack = (new Error()).stack; 5 | }; 6 | 7 | SpecifiedError.prototype = new Error(); 8 | SpecifiedError.prototype.constructor = SpecifiedError; 9 | 10 | module.exports = SpecifiedError; 11 | -------------------------------------------------------------------------------- /scripts/uglyHandler.js: -------------------------------------------------------------------------------- 1 | function uglyHandler(fn) { 2 | try { 3 | return fn(); 4 | } catch (e) { 5 | throw new Error('a new error'); 6 | } 7 | } 8 | 9 | if (typeof module === 'object') { 10 | module.exports = uglyHandler; 11 | } 12 | -------------------------------------------------------------------------------- /scripts/uglyHandlerDom.js: -------------------------------------------------------------------------------- 1 | (function (handler, bomb) { 2 | var uglyButton = document.getElementById('ugly'); 3 | 4 | if (uglyButton) { 5 | uglyButton.addEventListener('click', function () { 6 | handler(bomb); 7 | }); 8 | } 9 | }(uglyHandler, error)); 10 | -------------------------------------------------------------------------------- /scripts/uglyHandlerImproved.js: -------------------------------------------------------------------------------- 1 | var SpecifiedError = require('./specifiedError'); 2 | 3 | function uglyHandlerImproved(fn) { 4 | try { 5 | return fn(); 6 | } catch (e) { 7 | throw new SpecifiedError(e.message); 8 | } 9 | } 10 | 11 | module.exports = uglyHandlerImproved; 12 | -------------------------------------------------------------------------------- /tests/engines/httpHandlerTest.js: -------------------------------------------------------------------------------- 1 | var target = require('../../engines/httpHandler'); 2 | var response = require('./responseMock'); 3 | 4 | describe('An HTTP engine', function () { 5 | it('handles errors', function () { 6 | var res = response(); 7 | target({ message: 'error' }, res); 8 | res.getResult().should.equal('500text/plain; charset=utf-8Error: error'); 9 | }); 10 | 11 | it('handles responses', function () { 12 | var res = response(); 13 | var content = { type: 'type', response: 'message' }; 14 | target(null, res, content); 15 | res.getResult().should.equal('200typemessage'); 16 | }); 17 | 18 | it('handles responses with no-cache', function () { 19 | var res = response(); 20 | var content = { type: 'type', response: 'message', nocache: true }; 21 | target(null, res, content); 22 | res.getResult().should.equal('200typeno-cachemessage'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /tests/engines/responseMock.js: -------------------------------------------------------------------------------- 1 | function response() { 2 | var result = ''; 3 | 4 | return { 5 | writeHead: writeHead, 6 | end: end, 7 | getResult: getResult 8 | }; 9 | 10 | function writeHead(returnCode, headers) { 11 | result += returnCode; 12 | for (var prop in headers) { 13 | if (headers.hasOwnProperty(prop)) { 14 | result += headers[prop]; 15 | } 16 | } 17 | } 18 | 19 | function end(body) { 20 | result += body; 21 | } 22 | 23 | function getResult() { 24 | return result; 25 | } 26 | } 27 | 28 | module.exports = response; 29 | -------------------------------------------------------------------------------- /tests/routes/indexRequestTest.js: -------------------------------------------------------------------------------- 1 | var request = require('supertest'); 2 | var app = require('../../app'); 3 | 4 | describe('Get index', function() { 5 | it('responds with html', function(done) { 6 | request(app) 7 | .get('/') 8 | .expect('Content-Type', /html/) 9 | .expect('Cache-Control', /no-cache/) 10 | .expect(200, done); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /tests/routes/logRequestTest.js: -------------------------------------------------------------------------------- 1 | var request = require('supertest'); 2 | var app = require('../../app'); 3 | 4 | describe('Post log', function () { 5 | it('responds with json', function (done) { 6 | request(app) 7 | .post('/log') 8 | .expect('Content-Type', /json/) 9 | .expect('Cache-Control', /no-cache/) 10 | .expect(200, done); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /tests/routes/scriptRequestTest.js: -------------------------------------------------------------------------------- 1 | var request = require('supertest'); 2 | var app = require('../../app'); 3 | 4 | describe('Get script', function () { 5 | it('responds with javascript', function (done) { 6 | request(app) 7 | .get('/scripts/error.js') 8 | .expect('Content-Type', /javascript/) 9 | .expect(200, done); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /tests/scripts/asyncHandlerTest.js: -------------------------------------------------------------------------------- 1 | var asyncHandler = require('../../scripts/asyncHandler'); 2 | var should = require('should'); 3 | 4 | describe('An async error handler', function () { 5 | it('does not throw exceptions without errors', function (done) { 6 | var fn = function () { 7 | done(); 8 | }; 9 | 10 | should.doesNotThrow(function () { 11 | asyncHandler(fn); 12 | }); 13 | }); 14 | 15 | it('does not catch exceptions with errors', function () { 16 | var fn = function () { 17 | throw new TypeError('type error'); 18 | }; 19 | 20 | should.doesNotThrow(function () { 21 | asyncHandler(fn); 22 | }); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /tests/scripts/badHandlerTest.js: -------------------------------------------------------------------------------- 1 | var badHandler = require('../../scripts/badHandler'); 2 | var should = require('should'); 3 | 4 | describe('A bad error handler', function() { 5 | it('returns a value without errors', function() { 6 | var fn = function() { 7 | return 1; 8 | }; 9 | 10 | var result = badHandler(fn); 11 | 12 | result.should.equal(1); 13 | }); 14 | 15 | it('returns a null with errors', function() { 16 | var fn = function() { 17 | throw new Error('random error'); 18 | }; 19 | 20 | var result = badHandler(fn); 21 | 22 | should(result).equal(null); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /tests/scripts/errorTest.js: -------------------------------------------------------------------------------- 1 | var bomb = require('../../scripts/error'); 2 | var should = require('should'); 3 | 4 | describe('An error', function () { 5 | it('throwns a TypeError', function () { 6 | should.throws(bomb, TypeError); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /tests/scripts/uglyHandlerImprovedTest.js: -------------------------------------------------------------------------------- 1 | var uglyHandlerImproved = require('../../scripts/uglyHandlerImproved'); 2 | var SpecifiedError = require('../../scripts/specifiedError'); 3 | var should = require('should'); 4 | 5 | describe('An ugly error handler with improvements', function () { 6 | it('returns a value without errors', function () { 7 | var fn = function () { 8 | return 1; 9 | }; 10 | 11 | var result = uglyHandlerImproved(fn); 12 | 13 | result.should.equal(1); 14 | }); 15 | 16 | it('returns a specified error with errors', function () { 17 | var fn = function () { 18 | throw new TypeError('type error'); 19 | }; 20 | 21 | should.throws(function () { 22 | uglyHandlerImproved(fn); 23 | }, SpecifiedError); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /tests/scripts/uglyHandlerTest.js: -------------------------------------------------------------------------------- 1 | var uglyHandler = require('../../scripts/uglyHandler'); 2 | var should = require('should'); 3 | 4 | describe('An ugly error handler', function () { 5 | it('returns a value without errors', function () { 6 | var fn = function () { 7 | return 1; 8 | }; 9 | 10 | var result = uglyHandler(fn); 11 | 12 | result.should.equal(1); 13 | }); 14 | 15 | it('returns a new error with errors', function () { 16 | var fn = function () { 17 | throw new TypeError('type error'); 18 | }; 19 | 20 | should.throws(function () { 21 | uglyHandler(fn); 22 | }, Error); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 |11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | --------------------------------------------------------------------------------