README
express-murder
Small Express tool for quickly setting a status code and throwing an error. Designed to be used inside Express middleware. ECMAScript 5.1 compatible!
Installation
npm install express-murder --save
Usage
To use express-murder in your project, require it.
require('express-murder')
Now the express response prototype has had the .murder() function added.
If you wish to use the error handler included with it, access it by using:
require('express-murder').errorHandler
There are 2 tools included within express-murder, the 'response.murder()' function and the sample error handler.
response.murder()
The response.murder() function sets the response's HTTP status code, then throws an Error with the appropriate text.
Both the error text and status code can be changed by providing arguments to the function in this fashion:
response.murder(statusCode, errorText)
None of the arguments are required though, and if none are specified it uses 500 as the status and 'Internal Server Error' as the text.
If only a status code is specified, the text is loaded from this JSON stored within the .js file:
{
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"413": "Request Entity Too Large",
"414": "Request-URI Too Long",
"429": "Too Many Requests",
"451": "Unavailable For Legal Reasons",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported"
}
If you want a more verbose way of writing response.murder()
, you can use the alias response.statusThrow()
.
Both are identical.
errorHandler Middleware
The example errorHandler middleware is an example of a proper error handler that works well with thrown errors and status codes. It can be used in a project on its own, or expanded apon by reviewing the source.
An example snippet from an application demonstrating its use:
app.get('/', function (request, response) {
response.murder(404);
});
app.use(require('express-murder').errorHandler);
Output (text viewed in browser):
404, Not Found
The source for the handler is also extremely simple:
function errorHandler(err, req, res) {
res.send(res.statusCode + ', ' + err.message);
if (res.statusCode !== 404) {
error(err);
}
};
Tests
npm test
npm run coverage
Versioning
Like most NPM modules we use SemVer for versioning, although we are still on 1.0.0.
License
This module is licensed under the MIT License.