express-rendertype
v1.2.0
Published
Express middleware to (automatically) render content and errors to content-type
Downloads
21
Maintainers
Readme
express-rendertype
Express middleware to (automatically) render content and errors to content-type
This is basically a mashup of
- express-errs (Rails-inspired error handler for Express applications), and
- errorhandler (full stack traces and util.inspect of objects),
- a nod to express-error-responses,
- with a helper for restify/errors Error Classes thrown in.
Installation
npm install --save express-rendertype
Usage
render = require "express-rendertype"
app = express()
Rendering content
render.auto(fallback = false, preference = ["yaml", "json", "html", "text"])
create a .rendr method on the res object, falling back to json as default
app.use render.auto "json"
res.rendr(path = "", obj)
render to json or whichever content-type the client accepts
app.get "/someroute", (req, res, next) -> res.rendr "path/to/template", obj
Rendering errors
Status code
pass an error from just a status code
app.post "/noauthroute", (req, res, next) -> next status: 401
Error library
create an error with stacktrace in context from a status code
app.put "/payme", (req, res, next) -> next render.error.fromCode 402
throw an error with message from the error library
app.get "/gatekeeper", (req, res, next) ->
throw new render.error.LockedError "I am the keymaster"
See also: restify/errors
Objects
pass an object as the error
app.delete "/session", (req, res, next) -> next {foo: "bar", baz: "booze"}
(Fancy) Error-handling middleware
add the error-handling middleware after all routes
app.get ...
app.post ...
app.put ...
...
app.use render.FancyErrors.auto "text" if (@app.get "env") is "development"
app.use render.Errors.auto()
render.FancyErrors.auto(fallback, preference, log)
render.Errors.auto(fallback, preference, log)
Errors and FancyErrors are the same, except FancyErrors will log the stack to all content-types. FancyErrors even has a nice code excerpt when rendered to HTML.
app.use render.Errors.auto "html", ["html", "json"], console.log
MIT Licensed. (C) 2016 doublerebel