Coder Social home page Coder Social logo

oresoftware / domain-haven Goto Github PK

View Code? Open in Web Editor NEW
5.0 3.0 0.0 125 KB

Express middleware - pin runtime errors to a request/response pair using domains. Helps avoid needlessly shutting down servers.

License: MIT License

JavaScript 24.77% TypeScript 74.70% Shell 0.53%
nodejs node-core nodecore expressjs express-middleware

domain-haven's Introduction

Domain-Haven

Caveat

Works on Node.js version before 12. Currently not working on Node.js version 12.

About

This is an awesome module for using Node.js domains to capture runtime errors and
pin errors / exceptions / unhandled-rejections to a particular request/response.

import * as express from 'express';
import haven from 'domain-haven';

const app = express();
app.use(haven());

export {app};

In Production

### use these env vars to switch off stack-traces from leaking sensitive data to client(s):

export NODE_ENV=prod
export NODE_ENV=production
export DOMAIN_HAVEN_PROD=true

alternatively, use this option to not reveal stack-traces programmatically:

import * as haven from 'domain-haven';

haven.middleware({
  opts: {
    revealStackTraces: false
  }
});

// where the above is equivalent to:

import haven from 'domain-haven';

haven({
  opts: {
    revealStackTraces: false
  }
});

In Production, continued:

In some rare cases, we may wish to enable stack traces shown to the client for a particular request. You can override behavior for a particular request by doing this:

app.use((req,res,next) => {
  if(req.query.secret === 'magic-spell'){  // you control this, serverside
    req.havenOpts = {revealStackTraces: true, overrideProd: true};
  }
  next()
});

Behavior

By default, if an uncaughtException or unhandledRejection occurs and a request/response pair can be
pinned to the event, a JSON error response will be sent. If the event cannot be pinned to
to a particular request/response, Haven will shutdown the process.


On the other hand, if the developer wants full control of what response to send, etc, use:

app.use(haven({opts:{auto:false}}));

Performance

TBD

Usage

TBD

If you just want to capture errors that don't make it to the global scope, use:

app.use(haven({handleGlobalErrors: false}));

To just show error messages, but not the full stack trace, use:

app.use(haven({showStackTracesInResponse: false}));

How it works:

What we do is use something similar to this beautiful piece of middleware:

const havenMiddleware = function (req, res, next) {
    
    const d = domain.create(); // create a new domain for this request
    
    res.once('finish', () => {
      d.exit();
    });
    
    d.once('error',  (e) => {
        res.status(500).json({error: e});
    });
    
    d.run(next);  // we invoke the next middleware
    
};

domain-haven's People

Contributors

oresoftware avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

domain-haven's Issues

allow user to pass cleanup function

this will allows users to do memory management for resources that need to be cleaned up.

something like this:

app.use(haven({

},(req, res) => {
   
     

}));

or:

app.use(haven({
   cleanup(req){
        
   }
});

Uncaught exception could NOT be pinned to a request/response

Hi! read your medium article and I wanted to test this out, I have a simple sample:

const haven = require ('domain-haven')
const express = require('express')
const app = express()
console.log(haven);

app.use(haven.default());
const port = 3001



app.get('/', (req, res) => {

	try {
  setTimeout(function () {
    throw new Error('Fail!')
  }, Math.round(Math.random()*100))
} catch (e) {
  console.log('Custom Error: ' + e.message)
}

res.status(200).send("Ok!");

});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

And I am getting the error:

haven stderr: Uncaught exception could NOT be pinned to a request/response: { Error: Fail!

I am really hoping to use this on our production express app where one crash takes down the whole server and kills all the valid requests waiting behind the one invalid one. Will this work for that use case and can you tell me what's wrong with the above sample if anything in context of your middle-ware?

Thanks a lot!

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.