• callback {Function} The callback function
    • Returns: {Function} The intercepted function

    This method is almost identical to [domain.bind(callback)][]. However, in addition to catching thrown errors, it will also intercept [Error][] objects sent as the first argument to the function.

    In this way, the common if (err) return callback(err); pattern can be replaced with a single error handler in a single place.

    1. const d = domain.create();
    2. function readSomeFile(filename, cb) {
    3. fs.readFile(filename, 'utf8', d.intercept((data) => {
    4. // Note, the first argument is never passed to the
    5. // callback since it is assumed to be the 'Error' argument
    6. // and thus intercepted by the domain.
    7. // If this throws, it will also be passed to the domain
    8. // so the error-handling logic can be moved to the 'error'
    9. // event on the domain instead of being repeated throughout
    10. // the program.
    11. return cb(null, JSON.parse(data));
    12. }));
    13. }
    14. d.on('error', (er) => {
    15. // An error occurred somewhere. If we throw it now, it will crash the program
    16. // with the normal line number and stack message.
    17. });