Coder Social home page Coder Social logo

error's Introduction

koa-error

Error response middleware for koa supporting:

  • text
  • json
  • html

Installation

$ npm install koa-error

Options

  • template path to template written with your template engine, default: ./error.html
  • engine template engine name passed to consolidate, default: lodash
  • cache cached compiled functions, default: NODE_ENV != 'development'
  • env force a NODE_ENV, default: development
  • accepts mimetypes passed to ctx.accepts, default: [ 'html', 'text', 'json' ]

Custom templates

By using the template option you can override the bland default template, with the following available local variables:

  • env
  • ctx
  • request
  • response
  • error
  • stack
  • status
  • code

Here are some examples:

Pug (formerly jade)

app.use(error({
  engine: 'pug',
  template: __dirname + '/error.pug'
}));
doctype html
html
  head
    title= 'Error - ' + status
  body
    #error
      h1 Error
      p Looks like something broke!
      if env == 'development'
        h2 Message:
        pre: code= error
        h2 Stack:
        pre: code= stack

Nunjucks

app.use(error({
  engine: 'nunjucks',
  template: __dirname + '/error.njk'
}));
<!DOCTYPE html>
<html>
  <head>
    <title>Error - {{status}}</title>
  </head>
  <body>
    <div id="error">
      <h1>Error</h1>
    <p>Looks like something broke!</p>
    {% if env == 'development' %}
      <h2>Message:</h2>
      <pre>
        <code>
{{error}}
        </code>
      </pre>
      <h2>Stack:</h2>
      <pre>
        <code>
{{stack}}
        </code>
      </pre>
    {% endif %}
    </div>
  </body>
</html>

License

MIT

error's People

Contributors

bredikhin avatar dantman avatar eduardorfs avatar fengb avatar haoxins avatar jonathanong avatar kudos avatar matthewmueller avatar millette avatar remoe avatar rynz avatar tj avatar vwkd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

error's Issues

text/html defaults to text

Not sure if this is an error in req.accepts() or koa-errors switch logic.

I was trying to get an html error template working but would only ever get the text error message.
My browsers sending Accepts: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
After debugging this.accepts('text', 'json', 'html') it returns only 'text' so it never gets to the 'html' part of the switch statement. Changing the code to switch(this.accepts('html', 'json', 'text')) {
The html template is used. I'm not sure of the implications of that change as I haven't spent much time trying to figure whats going on ;)
To clarify the change, I switched the 'html' and 'text' values so html is first in the this.accepts() call

Add custom filters and use extend/include the macro/block in view template engine like nunjucks

Use filters & include other tpl code in Nunjucks engine PR36

Directory:

   /
   ├─ app.js
   │
   ├─ filters.js
   │
   └─ tpl
       │
       ├─ com.html
       │
       └─ error.html

tpl/error.html:

<!DOCTYPE html>
<html>
  <head>
    {% include "./com.html" %}
  </head>
  <body>
    <p>{{ request | stringify }}</p> {# use filters here #}
    <!-- ... -->
  </body>
</htm>

tpl/com.html:

<link rel="stylesheet" href="/css/normalize.css" />

filters.js:

module.exports = { 
    // define filters function here
    stringify(..args){
        return JSON.stringify(...args);
    }
    //...
};

app.js:

//...
const nunjucks = require('nunjucks');
const nunjucksEnv = new nunjucks.Environment(
    new nunjucks.FileSystemLoader(path.join(__dirname, 'tpl'))
);
// add filters
const filters = require('./filters');
for(let [k,v] of Object.entries(filters)){
    nunjucksEnv.addFilter(k, v);
}
//...
app.use(koaError({
    //...
    template: path.join(__dirname, 'tpl/error.html'),
    options: {
        nunjucksEnv // custom nunjucks env
    }
}));

Prevent node's default action when emitting "error"

When an EventEmitter instance experiences an error, the typical action is to emit an 'error' event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.

This is a terrible, terrible default. Right now it's exiting our the program before hitting the switch statement if you don't have your own app level listeners.

stream error

we only do try catch here to catch the error.
but all the streams' and events' errors are handling by stream.on('error', this.onerror), we can do nothing for them, except hack ctx.onerror method.

should we add an easy way for users to write their own error handler in koa, just like what connect/express do:

app.use(function (err, req, res, next){});

or just leave these to error middleware with hack ctx.onerror?

koa-error doesn't depend on the template engine it uses by default

When the switch was made to consolidate koa-error stopped depending on swig, however the default template is still swig.

This means that unless the parent app either depends on swig or defines its own template and requires a template engine for it; using koa-error will now result in an Error: Cannot find module 'swig' error.

Include a better default templating engine

Per #19 (comment), koa-error is defaulting to a library (Swig) that is no longer maintained, and also is causing nsp to error out due to an out-of-date uglify-js dependency.

Something more current, more widely used, and maintained should be swapped in.

I would suggest one of the following:

  • ejs
  • mustachJS
  • handlebarsJS

Better yet. This could just be done using ES6 JS string templating and remove the dependency all together ;-)

Swig throws in strict mode

$ node --use-strict example.js
/home/parkle/dev/koa-error/node_modules/swig/lib/utils.js:143
        target[key] = obj[key];
                    ^

TypeError: Cannot assign to read only property 'name' of function compiled(locals) {
      var lcls;
      if (locals && contextLength) {
        lcls = utils.extend({}...<omitted>... }
    at Object.exports.extend (/home/parkle/dev/koa-error/node_modules/swig/lib/utils.js:143:21)
    at compile (/home/parkle/dev/koa-error/node_modules/swig/lib/swig.js:622:11)
    at Object.compileFile (/home/parkle/dev/koa-error/node_modules/swig/lib/swig.js:696:17)
    at error (/home/parkle/dev/koa-error/index.js:28:21)
    at Object.<anonymous> (/home/parkle/dev/koa-error/example.js:10:9)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)

Would be great if koa-error could be used in strict mode, thanks!

using err.expose and NODE_ENV

Since I am building an API I would like to have my errors to be descriptive in test and production environment too.

I noticed the use of err.expose, can you show me an use case for example of a signin error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.