Do something and throw an error with enhanced exception (from given source)

@param {Function} fn     [description]
@param {[type]}   source [description]
199022
function tryCatch(fn, source) {
  try {
    return fn()
  }
  catch (err) {
    err.originalMessage = err.message
    err.message = formatMessage(err.message, source)

    // if source seems interesting, enhance error
    if (typeof source === "object") {
      // add a stack item if something interesting available
      if ((source.input && source.input.file) || source.start) {
        var stack = err.stack.split(SPLITTER)
        var firstStackItem = stack.shift()
        stack.unshift(sourceString(source))
        stack.unshift(firstStackItem)
        err.stack = stack.join(SPLITTER)
      }

      if (source.input && source.input.file) {
        err.fileName = source.input.file
      }
      if (source.start) {
        err.lineNumber = source.start.line
        err.columnNumber = source.start.column
      }
    }

    throw err
  }
}
1315657
function Exception(code, message) {
    const factory = Object.create(Exception.prototype);
    factory.code = code;
    factory.message = message;
    factory.stack = factory.toString();
    return factory;
}
1049396
def template_exception_handler(fn, error_context, filename=None):
    """"""
    error_message = None
    if filename:
        error_context.update(filename=filename)
    try:
        return fn()
    except jinja2.TemplateSyntaxError as exc:
        error_context.update(filename=exc.filename, line_no=exc.lineno)
        error_message = exc.message
    except jinja2.TemplateError as exc:
        error_message = exc.message
    except Exception as exc:
        error_message = "%s" % exc

    raise TemplateError(message=error_message, context=error_context)
370367
def handle_errors(f):
    
    import traceback
    from plone.jsonapi.core.helpers import error

    def decorator(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception:
            var = traceback.format_exc()
            return error(var)

    return decorator
379269
function sourceFromStacktrace() {
	try {
		throw new Error();
	} catch ( e ) {
		if (e.stacktrace) {
			// Opera
			return e.stacktrace.split("\n")[6];
		} else if (e.stack) {
			// Firefox, Chrome
			return e.stack.split("\n")[4];
		} else if (e.sourceURL) {
			// Safari, PhantomJS
			// TODO sourceURL points at the 'throw new Error' line above, useless
			//return e.sourceURL + ":" + e.line;
		}
	}
}
629699
function attempt(fn){
		try {
			var args = _.from(arguments);
			args.shift();
			
			return fn.apply(this, args);
		} catch(e){
			return false;
		}
	}
104310
function removeErrorRecovery (fn) {
    var parseFn = String(fn);
    try {
        var JSONSelect = require("JSONSelect");
        var Reflect = require("reflect");
        var ast = Reflect.parse(parseFn);

        var labeled = JSONSelect.match(':has(:root > .label > .name:val("_handle_error"))', ast);
        labeled[0].body.consequent.body = [labeled[0].body.consequent.body[0], labeled[0].body.consequent.body[1]];

        return Reflect.stringify(ast).replace(/_handle_error:\s?/,"").replace(/\\\\n/g,"\\n");
    } catch (e) {
        return parseFn;
    }
}
422494
function (fn) {
    if (!fn || !_.isFunction(fn)) {
      var err = new Error('Please pass a valid function!');
      debug(err);
      throw err;
    }

    if (fn.length === 3) {
      this.shouldHandle = fn;
      return this;
    }

    this.shouldHandle = function (evt, saga, callback) {
      callback(null, fn(evt, saga));
    };

    var unwrappedShouldHandle = this.shouldHandle;

    this.shouldHandle = function (evt, saga, clb) {
      var wrappedCallback = function () {
        try {
          clb.apply(this, _.toArray(arguments));
        } catch (e) {
          debug(e);
          process.emit('uncaughtException', e);
        }
      };

      try {
        unwrappedShouldHandle.call(this, evt, saga, wrappedCallback);
      } catch (e) {
        debug(e);
        process.emit('uncaughtException', e);
      }
    };

    return this;
  }
257544
function errHandler(err) {
    /* istanbul ignore else */
    if (_output) {
      err = err instanceof Error ? err : new Error(err)
      _emitter.emit('end', err)
      _output = null
    }
    else
      console.error('jspreproc: ' + err)
  }
645606
function error () {
  if (mocking) {
    cli.stderr += stripAnsi(concatArguments(arguments) + '\n')
  } else {
    console.error.apply(null, arguments)
  }
}
965447
function onError(error) {
  	for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  		args[_key - 1] = arguments[_key];
  	}

  	if (config.current) {
  		if (config.current.ignoreGlobalErrors) {
  			return true;
  		}
  		pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  	} else {
  		test("global failure", extend(function () {
  			pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  		}, { validTest: true }));
  	}

  	return false;
  }
705740
function(err) {
		/**
		 * If err is an Error object, break the chain and call catch
		 */
		if (err && (err.constructor.name === "Error" || err.constructor.name === "TypeError") && this.onCatch) {
			this.onCatch(err);
			return;
		}

		var nextFn = this.fnStack.shift();
		if (nextFn) {
			/**
			 * Ensure arguments are passed as an Array
			 */
			var args = Array.prototype.slice.call(arguments);
			return this.execute(nextFn.fn, args);
		}
	}
126931
function _runError(error, module) {
  const _error = new emitter.Error({
    target:module.filename,
    source:(module.parent || module).filename,
    error
  });
  module.exports = _error;
  emitter.emit('error', _error);
  return (!!_error.ignore || (_error.ignore && isFunction(_error.ignore) && _error.ignore()));
}
558737
function _gpfErrorDeclare (source, dictionary) {
    _gpfIgnore(source);
    _gpfObjectForEach(dictionary, function (message, name) {
        var code = ++_gpfLastErrorCode;
        gpf.Error["CODE_" + name.toUpperCase()] = code;
        gpf.Error[name] = _gpfGenenerateErrorFunction(code, name, message);
    });
}
494097
function onOutError(err) {
    errNodecat = combineErrors(errNodecat, err);
    errStream.write(`nodecat: ${err}\n`);
    if (inCleanup) {
      inCleanup();
    }
    allDone();
  }
354827
function check(source, file) {
  if (t.isLiteral(source)) {
    var name = source.value;
    var lower = name.toLowerCase();

    if (lower === "react" && name !== lower) {
      throw file.errorWithNode(source, messages.get("didYouMean", "react"));
    }
  }
}
329839
function throwIf (target /*, illegal... */) {
    Array.prototype.slice.call(arguments, 1).forEach(function (name) {
      if (options[name]) {
        throw new Error('Cannot set ' + name + ' and ' + target + 'together');
      }
    });
  }