Handle various client side errors when describing images
358983
def extract_bad_ami(e):
        """"""
        msg = e.response['Error']['Message']
        error = e.response['Error']['Code']
        e_ami_ids = None
        if error == 'InvalidAMIID.NotFound':
            e_ami_ids = [
                e_ami_id.strip() for e_ami_id
                in msg[msg.find("'[") + 2:msg.rfind("]'")].split(',')]
            log.warning("Image not found %s" % e_ami_ids)
        elif error == 'InvalidAMIID.Malformed':
            e_ami_ids = [msg[msg.find('"') + 1:msg.rfind('"')]]
            log.warning("Image id malformed %s" % e_ami_ids)
        return e_ami_ids
1130716
function callback(err, callbackId) {
    // There is a single callback for all load events, so make sure this
    // is the right one.
    if (callbackId !== imageId) {
      return;
    }

    stage.removeFlashCallbackListener('imageLoaded', callback);

    // TODO: is there any way to distinguish a network error from other
    // kinds of errors? For now we always return NetworkError since this
    // prevents images to be retried continuously while we are offline.
    if (err) {
      done(new NetworkError('Network error: ' + url));
    } else {
      done(null, new FlashAsset(flashElement, imageId));
    }
  }
1096894
def handle_error(self, request: Any, status: int = 500, exc: Any = None, message: Optional[str] = None) -> web.Response:
        """"""
        if self.transport is None:
            # client has been disconnected during writing.
            if self._access_log:
                request_ip = RequestHandler.get_request_ip(request, None)
                version_string = None
                if isinstance(request.version, HttpVersion):
                    version_string = 'HTTP/{}.{}'.format(request.version.major, request.version.minor)
                logging.getLogger('transport.http').info('[{}] [{}] {} {} "{} {}{}{}" - {} "{}" -'.format(
                    RequestHandler.colorize_status('http', 499),
                    RequestHandler.colorize_status(499),
                    request_ip or '',
                    '"{}"'.format(request._cache['auth'].login.replace('"', '')) if request._cache.get('auth') and getattr(request._cache.get('auth'), 'login', None) else '-',
                    request.method,
                    request.path,
                    '?{}'.format(request.query_string) if request.query_string else '',
                    ' {}'.format(version_string) if version_string else '',
                    request.content_length if request.content_length is not None else '-',
                    request.headers.get('User-Agent', '').replace('"', '')
                ))

        headers = {}
        headers[hdrs.CONTENT_TYPE] = 'text/plain; charset=utf-8'

        msg = '' if status == 500 or not message else message

        headers[hdrs.CONTENT_LENGTH] = str(len(msg))
        headers[hdrs.SERVER] = self._server_header or ''
        resp = web.Response(status=status,  # type: ignore
                            text=msg,
                            headers=headers)  # type: web.Response
        resp.force_close()  # type: ignore

        # some data already got sent, connection is broken
        if request.writer.output_size > 0 or self.transport is None:
            self.force_close()  # type: ignore
        elif self.transport is not None:
            request_ip = RequestHandler.get_request_ip(request, None)
            if not request_ip:
                peername = request.transport.get_extra_info('peername')
                if peername:
                    request_ip, _ = peername
            if self._access_log:
                logging.getLogger('transport.http').info('[{}] [{}] {} {} "INVALID" {} - "" -'.format(
                    RequestHandler.colorize_status('http', status),
                    RequestHandler.colorize_status(status),
                    request_ip or '',
                    '"{}"'.format(request._cache['auth'].login.replace('"', '')) if request._cache.get('auth') and getattr(request._cache.get('auth'), 'login', None) else '-',
                    len(msg)
                ))

        return resp
659183
function(err, imageIdentifier, res) {
        // Remove progress bar
        bar.css('width', '100%');
        progress.animate({ opacity: 0}, {
            duration: 1000,
            complete: function() {
                $(this).remove();
            }
        });

        // Check for any XHR errors (200 means image already exists)
        if (err && res && res.headers && res.headers['X-Imbo-Error-Internalcode'] !== 200) {
            if (err === 'Signature mismatch') {
                err += ' (probably incorrect private key)';
            }

            /* eslint no-alert: 0 */
            return window.alert(err);
        } else if (err) {
            return window.alert(err);
        }

        // Build an Imbo-url
        var result = $('#result').removeClass('hidden');
        var url = client.getImageUrl(imageIdentifier);
        $('#image-identifier').text(imageIdentifier).attr('href', url.toString());
        result.find('img').attr('src', url.maxSize({ width: result.width() }).toString());
        updateUrl(url);

        if (!active) {
            $('#controls [data-transformation="border"]').on('click', function() {
                url.border({ color: 'bf1942', width: 5, height: 5 });
            });

            $('#controls button').on('click', function() {
                var btn = $(this),
                    transformation = btn.data('transformation'),
                    args = btn.data('args'),
                    pass = args ? (args + '').split(',') : [];

                url[transformation].apply(url, pass);

                if (transformation === 'reset') {
                    url.maxSize({ width: result.width() });
                }

                updateUrl(url);

                result.find('img').attr('src', url.toString());
            });
        }
    }
884208
function errorPage(res, err) {
		if (err) {
			console.error(err.message);
			res.send(err, {'Content-Type': 'text/plain'}, 500);
		} else {
			res.send(404);
		}
	}
860797
function errorHandler(error, req, res, next) {
    req.body.email = '';
    req.body.subscribed_url = santizeUrl(req.body.subscribed_url);
    req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer);

    if (error.statusCode !== 404) {
        res.locals.error = error;
        return _renderer(req, res);
    }

    next(error);
}
147295
public function showErrors()
    {
        $key = sprintf('images.%s.file', $this->inputId());
        if (session('errors') && ($error = session('errors')->first($key))) {
            $this->help($error);
            $this->group->addClass('has-error');
        }
    }
418851
function ClientError(message, status, cause) {
    ClientError.super_.call(this, message, status || StatusCode.CLIENT_ERROR, cause);
}
1004322
def error(code, message, template):
    """"""
    if json_requested():
        return json_error(code, message)
    else:
        return render_template(template, message=message), code
822456
function handleImageLoad(canvas, filename, e) {
        e.preventDefault();

        downloadCanvas(drawImageOnCanvas(this, canvas), filename);
    }
734500
function formatResponseError(resp) {
    let result;

    if (resp.data.error) {
        result = resp.data.error.detail || resp.data.error;
    }
    else {
        result = resp.data.detail || JSON.stringify(resp.data);
    }

    return result.replace(/\n/g, '');
}
1106662
def render_error_debug(request, exception, is_html):
    '''
    '''
    error = Html('div', cn='well well-lg') if is_html else []
    for trace in format_traceback(exception):
        counter = 0
        for line in trace.split('\n'):
            if line.startswith('  '):
                counter += 1
                line = line[2:]
            if line:
                if is_html:
                    line = Html('p', escape(line), cn='text-danger')
                    if counter:
                        line.css({'margin-left': '%spx' % (20*counter)})
                error.append(line)
    if is_html:
        error = Html('div', Html('h1', request.response.status), error)
    return error
813518
function htmlError(result, cb) {
  var message = result.body
    .match(/<h1>Error<\/h1>.+<\/p>/).toString()
    .replace(/<h1>Error<\/h1>/, '')
    .replace(/<\/?p>/g, '');
  cb(new Error(message));
}
924120
function handleError(res) {
  return function (err) {
    if (err.status && err.name !== 'NotFoundError') {
      // If we're in this block, the error has a defined `status` property and
      // the error should be directed out immediately
      sendDefaultResponseForCode(err.status, err.message, res);
    } else if (err.name === 'NotFoundError' ||
      err.message.indexOf('ENOENT') !== -1 ||
      err.message.indexOf('not found') !== -1) {
      notFound(err, res);
      // if the word "client" is ever in a message, it should be for the client.  We enforce that here.
    } else if (err.message.indexOf('Client') !== -1) {
      clientError(err, res);
    } else {
      serverError(err, res);
    }
  };
}
1236209
def handle_g_error(error, return_value):
    
    error = error[0]
    assert bool(return_value) == (error == ffi.NULL)
    if error != ffi.NULL:
        if error.message != ffi.NULL:
            message = ('Pixbuf error: ' +
                       ffi.string(error.message).decode('utf8', 'replace'))
        else:  # pragma: no cover
            message = 'Pixbuf error'
        glib.g_error_free(error)
        raise ImageLoadingError(message)
465953
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
		boolean includeStackTrace = isIncludeStackTrace(request, MediaType.ALL);
		Map<String, Object> error = getErrorAttributes(request, includeStackTrace);
		return ServerResponse.status(getHttpStatus(error))
				.contentType(MediaType.APPLICATION_JSON_UTF8)
				.body(BodyInserters.fromObject(error));
	}
1374302
protected void handleFeedImages(List<Pair<String, CharSequence>> params,
                                  Collection<IFeedImage> images) {
    if (images != null && images.size() > 4) {
      throw new IllegalArgumentException("At most four images are allowed, got " +
                                         Integer.toString(images.size()));
    }
    if (null != images && !images.isEmpty()) {
      int image_count = 0;
      for (IFeedImage image : images) {
        ++image_count;
        String imageUrl = image.getImageUrlString(); 
        assert null != imageUrl && "".equals(imageUrl) : "Image URL must be provided";
        params.add(new Pair<String, CharSequence>(String.format("image_%d", image_count),
                                                  image.getImageUrlString()));
        assert null != image.getLinkUrl() : "Image link URL must be provided";
        params.add(new Pair<String, CharSequence>(String.format("image_%d_link", image_count),
                                                  image.getLinkUrl().toString()));
      }
    }
  }