Last active
August 29, 2015 14:05
-
-
Save RobertFischer/11a6328f5bc58caf00ec to your computer and use it in GitHub Desktop.
Error Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Three functions: | |
One if the message is hard-coded. | |
One if the message is provided entirely by the user. | |
One if the message needs a suffix provided by the user. | |
You could also create a function that used JavaScript's sprintf | |
and the arguments object (cast to an object by _.toArray()) for | |
truly flexible error messaging. That is left as an exercise for | |
the team. | |
*/ | |
var err = function(code, msg) { | |
if(!code) throw "No HTTP status code provided"; | |
if(!msg) throw("No error message provided for code [" + code + "]"); | |
return function() { return {"code":code, "message":msg}; }; | |
}; | |
var errCode = function(code) { | |
if(!code) throw "No HTTP status code provided"; | |
return function(msg) { | |
if(!msg) throw("Please provide an error message for code [" + code + "]"); | |
return {"code":code, "message":msg}; | |
}; | |
}; | |
var errCodePrefix = function(code, prefix) { | |
if(!code) throw "No HTTP status code provided"; | |
if(!prefix) throw "No prefix provided: use errCode"; | |
return function(suffix) { | |
if(!suffix) throw("Please provide a suffix for code [" + code "] with prefix: " + prefix); | |
return {"code":code, "message":prefix + " " + suffix}; | |
} | |
}; | |
// Use this in this way: | |
// var errors = require("errors.js"); | |
// errors.UNKNOWN(); | |
// errors.login.BAD_USERNAME(username); | |
module.exports = { | |
UNKNOWN: err(500, "Unknown server error"), | |
login: { | |
BAD_USERNAME: errCodePrefix(400, "Username is not in the appropriate format: "); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is also a good example of precondition checking. Better would be to ensure that
code
is a number between 100 and 510.