From 90cb463390cda3afae419df4e8928485c7c099a0 Mon Sep 17 00:00:00 2001 From: Juan Cruz Viotti Date: Mon, 24 Nov 2014 14:00:35 -0400 Subject: [PATCH] Implement errors module --- lib/errors/errors.coffee | 14 ++++++++++ lib/errors/errors.spec.coffee | 49 +++++++++++++++++++++++++++++++++++ package.json | 3 ++- 3 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 lib/errors/errors.coffee create mode 100644 lib/errors/errors.spec.coffee diff --git a/lib/errors/errors.coffee b/lib/errors/errors.coffee new file mode 100644 index 00000000..a0bc738f --- /dev/null +++ b/lib/errors/errors.coffee @@ -0,0 +1,14 @@ +TypedError = require('typed-error') +log = require('../log/log') + +exports.NotFound = class NotFound extends TypedError + contructor: (name) -> + @message = "Couldn't find #{name}" + +exports.handle = (error, exit = true) -> + return if not error? or error not instanceof Error + + if error.message? + log.error(error.message) + + process.exit(1) if exit diff --git a/lib/errors/errors.spec.coffee b/lib/errors/errors.spec.coffee new file mode 100644 index 00000000..8b35a449 --- /dev/null +++ b/lib/errors/errors.spec.coffee @@ -0,0 +1,49 @@ +expect = require('chai').expect +sinon = require('sinon') +log = require('../log/log') +errors = require('./errors') + +MESSAGES = + helloWorld: 'Hello World' + +describe 'Errors:', -> + + describe '#handle()', -> + + it 'should log the error message to stderr', -> + logErrorStub = sinon.stub(log, 'error') + error = new Error(MESSAGES.helloWorld) + errors.handle(error, false) + expect(logErrorStub).to.have.been.calledWith(MESSAGES.helloWorld) + logErrorStub.restore() + + it 'should do nothing if error is not an instance of Error', -> + logErrorStub = sinon.stub(log, 'error') + + for item in [ + undefined + null + [ 1, 2, 3 ] + 'Hello' + { message: 'foo bar' } + ] + errors.handle(item, false) + + expect(logErrorStub).to.not.have.been.called + logErrorStub.restore() + + checkProcessExitOption = (value, expectations) -> + processExitStub = sinon.stub(process, 'exit') + logErrorStub = sinon.stub(log, 'error') + errors.handle(new Error(MESSAGES.helloWorld), value) + expectations(processExitStub) + processExitStub.restore() + logErrorStub.restore() + + it 'should exit if the last parameter is true', -> + checkProcessExitOption true, (processExitStub) -> + expect(processExitStub).to.have.been.called + + it 'should not exit if the last parameter is false', -> + checkProcessExitOption false, (processExitStub) -> + expect(processExitStub).to.not.have.been.called diff --git a/package.json b/package.json index 6d0d5890..6b133064 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "open": "0.0.5", "inquirer": "~0.8.0", "cliff": "~0.1.9", - "underscore.string": "~2.4.0" + "underscore.string": "~2.4.0", + "typed-error": "~0.1.0" } }