urlopen(), plus error handling and possible retries.

        err_env is a dict of additional info passed to the error handler
969814
def _call_api(self, api_url, err_env):
        
        while True:  # may retry on error
            api_request = urllib2.Request(
                api_url, headers={"Accept-Encoding": "gzip"})

            log.debug("Amazon URL: %s" % api_url)

            try:
                if self.Timeout and sys.version[:3] in ["2.4", "2.5"]:
                    # urllib2.urlopen() doesn't accept timeout until 2.6
                    old_timeout = socket.getdefaulttimeout()
                    try:
                        socket.setdefaulttimeout(self.Timeout)
                        return urllib2.urlopen(api_request)
                    finally:
                        socket.setdefaulttimeout(old_timeout)
                else:
                    # the simple way
                    return urllib2.urlopen(api_request, timeout=self.Timeout)
            except:
                if not self.ErrorHandler:
                    raise

                exception = sys.exc_info()[1]  # works in Python 2 and 3
                err = {'exception': exception}
                err.update(err_env)
                if not self.ErrorHandler(err):
                    raise
605692
function(err) {
    var errToStr = function(err) {
        var obj = {};
        Object.getOwnPropertyNames(err)
            .forEach(function(key) { obj[key] = err[key]; });
        return JSON.stringify(obj, null, 2);
    };

    var result = errToStr(err);
    if (typeof result === 'string') {
        result = result.replace(/\\n/g, '\n');
    }
    return result;
}
149937
def call_failure_app(env, options = {})
      if config.failure_app
        options.merge!(:attempted_path => ::Rack::Request.new(env).fullpath)
        env["PATH_INFO"] = "/#{options[:action]}"
        env["warden.options"] = options

        _run_callbacks(:before_failure, env, options)
        config.failure_app.call(env).to_a
      else
        raise "No Failure App provided"
      end
    end
640356
def error_handler(_, err, arg):
    """"""
    arg.value = err.error
    return libnl.handlers.NL_STOP
233472
function errHandler(err, req, res) {
    if (!err.status) { log(err); }
    error(err.status || 500, req, res, u.str(err));
  }
576276
function errorHandler( $errno, $errstr, $errfile, $errline )
    {
        if ( error_reporting() == 0 ) // @ error-control operator is used
            return;
        if ( !eZDebug::isDebugEnabled() )
            return;
        $str = "$errstr in $errfile on line $errline";
        if ( empty( $GLOBALS['eZDebugPHPErrorNames'] ) )
        {
            $GLOBALS['eZDebugPHPErrorNames'] =
                array( E_ERROR => 'E_ERROR',
                       E_PARSE => 'E_PARSE',
                       E_CORE_ERROR => 'E_CORE_ERROR',
                       E_COMPILE_ERROR => 'E_COMPILE_ERROR',
                       E_USER_ERROR => 'E_USER_ERROR',
                       E_WARNING => 'E_WARNING',
                       E_CORE_WARNING => 'E_CORE_WARNING',
                       E_COMPILE_WARNING => 'E_COMPILE_WARNING',
                       E_USER_WARNING => 'E_USER_WARNING',
                       E_NOTICE => 'E_NOTICE',
                       E_USER_NOTICE => 'E_USER_NOTICE',
                       E_STRICT => 'E_STRICT' );
            // Since PHP 5.2
            if ( defined('E_RECOVERABLE_ERROR') )
                $GLOBALS['eZDebugPHPErrorNames'][E_RECOVERABLE_ERROR] = 'E_RECOVERABLE_ERROR';
            // Since PHP 5.3
            if ( defined('E_DEPRECATED') )
                $GLOBALS['eZDebugPHPErrorNames'][E_DEPRECATED] = 'E_DEPRECATED';
            if ( defined('E_USER_DEPRECATED') )
                $GLOBALS['eZDebugPHPErrorNames'][E_USER_DEPRECATED] = 'E_USER_DEPRECATED';

        }
        $errname = "Unknown error code ($errno)";
        if ( isset( $GLOBALS['eZDebugPHPErrorNames'][$errno] ) )
        {
            $errname = $GLOBALS['eZDebugPHPErrorNames'][$errno];
        }
        switch ( $errname )
        {
            case 'E_ERROR':
            case 'E_PARSE':
            case 'E_CORE_ERROR':
            case 'E_COMPILE_ERROR':
            case 'E_USER_ERROR':
            case 'E_RECOVERABLE_ERROR':
            {
                $this->writeError( $str, 'PHP: ' . $errname );
            } break;

            case 'E_WARNING':
            case 'E_CORE_WARNING':
            case 'E_COMPILE_WARNING':
            case 'E_USER_WARNING':
            case 'E_DEPRECATED':
            case 'E_USER_DEPRECATED':
            {
                $this->writeWarning( $str, 'PHP: ' . $errname );
            } break;

            case 'E_NOTICE':
            case 'E_USER_NOTICE':
            {
                $this->writeNotice( $str, 'PHP: ' . $errname );
            } break;

            case 'E_STRICT':
            {
                return $this->writeStrict( $str, 'PHP: ' . $errname );
            } break;
            default:
            {
                 $this->writeError( $str, 'PHP: ' . $errname );
            } break;
        }
    }
494097
function onOutError(err) {
    errNodecat = combineErrors(errNodecat, err);
    errStream.write(`nodecat: ${err}\n`);
    if (inCleanup) {
      inCleanup();
    }
    allDone();
  }
1169982
function defaultErrorHandler(err, req, res) {
  if (err.name === 'UnauthorizedError') { // authentication is expected to be a common use-case
    res.status(401).end();
  } else {
    if (!err.status || err.status >= 500) {
      console.error(err.stack || err.toString());
    }
    res.status(err.status || 500).json({message: err.message})
  }
}
1337615
function handleError(err) {
  let errMsg = err;

  if (err instanceof Object) {
    errMsg = err.message || err.error || JSON.stringify(err);
  }

  printColumns(chalk.red('Error: ' + errMsg));
  printColumns(
    chalk.white(
      "If you can't settle this, please open an issue at:" + EOL + chalk.cyan(pkg.bugs.url)
    )
  );
  process.exit(1);
}
1083429
function proxyError(err) {
    errState = true;

    //
    // Emit an `error` event, allowing the application to use custom
    // error handling. The error handler should end the response.
    //
    if (self.emit('proxyError', err, req, res)) {
      return;
    }

    res.writeHead(500, { 'Content-Type': 'text/plain' });

    if (req.method !== 'HEAD') {
      //
      // This NODE_ENV=production behavior is mimics Express and
      // Connect.
      //
      if (process.env.NODE_ENV === 'production') {
        res.write('Internal Server Error');
      }
      else {
        res.write('An error has occurred: ' + JSON.stringify(err));
      }
    }

    try { res.end() }
    catch (ex) { console.error("res.end error: %s", ex.message) }
  }
385994
def error_handler(f):
    """"""
    @wraps(f)
    def decorated(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except OAuth2Error as e:
            # Only FatalClientError are handled by Flask-OAuthlib (as these
            # errors should not be redirect back to the client - see
            # http://tools.ietf.org/html/rfc6749#section-4.2.2.1)
            if hasattr(e, 'redirect_uri'):
                return redirect(e.in_uri(e.redirect_uri))
            else:
                return redirect(e.in_uri(oauth2.error_uri))
    return decorated
578441
function (err, body) {
          if (!err) {
            var val = body.GET
            if (val) {
              /*
              {
                "GET": "[resource]@[id]"
              }
              */
              val = val.split('@')
              // overwrite body
              body = {
                'resource': val[0],
                '_id': val[1]
              }

              // success, pass the object
              callback(null, body)
            } else {
              // Redis key not found
              body = {
                'status': 404,
                'error_code': -44,
                'message': 'Page not found, invalid slug or store ID'
              }
              var msg = body.message
              errorHandling(callback, msg, body)
            }
          } else {
            // just pass the error
            callback(err, body)
          }
        }
941141
function errnoException(err, syscall, address, port) {
		var errname;
		var message;
		if ((typeof err === 'undefined' ? 'undefined' : _typeof(err)) == 'object') {
			errname = errorCodes[err.number] || err.number;
			message = syscall + ' ' + errname + ' ' + err.message;
		} else {
			errname = err;
			message = syscall + ' ' + errname;
		}
		var e = new Error(message);
		e.code = e.errno = errname;
		e.syscall = syscall;
		if (port) {
			e.port = port;
		}
		if (address) {
			e.address = address;
		}
		return e;
	}
518180
def __error_middleware(self, res, res_json):
        
        if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]):
            err_dict = res_json.get('error', {})
            raise UpCloudAPIError(error_code=err_dict.get('error_code'),
                                  error_message=err_dict.get('error_message'))

        return res_json
910722
function(err, req, res) {

  console.log('handle error:');
  console.dir(err);

  // uri error
  if (err instanceof URIError) {
    return res.status(404).render('errors/404');
  }

  logger.error(req.method + ' ' + getURL(req) + ' : ' + err);
  logger.error(err.stack);

  if (!res._headerSent) {
    // show error
    if (config.showerrstack) {
      //
      const stacktrace = [
        '<h1>', req.originalUrl, '</h1>',
        '<pre>', err.stack, '</pre>'
      ].join('');
      res.status(500).send(stacktrace);
    } else {
      res.status(500).render('errors/500');
    }
  }

  if (config.mailcrashto) {
    mailer.send('crash', {
      to:       config.mailcrashto,
      subject:  [ config.appname, 'Crash:', err ].join(' '),
      body:     formatMessage(req, err)
    })
  }
}
900005
function webpack_error_handler (err, stats, callback) {

  if(err) throw new gutil.PluginError('webpack', err);
  if(PRODUCTION){
    gutil.log('[webpack]', stats.toString({
        // output options
        source: false
    }));
  } else {
    var jsonStats = stats.toJson({
      errorDetails: false
    });
    if(jsonStats.errors.length > 0){
        gutil.log(gutil.colors.red('ERROR\n' + jsonStats.errors.join('\n')));
    }
    if(jsonStats.warnings.length > 0){
        gutil.log(gutil.colors.yellow('WARNING\n' + jsonStats.warnings.join('\n')));
    }
  }

  callback();
}
884208
function errorPage(res, err) {
		if (err) {
			console.error(err.message);
			res.send(err, {'Content-Type': 'text/plain'}, 500);
		} else {
			res.send(404);
		}
	}