Text rendering of error response.

        Designed for use with Image API version 1.1 and above where the
        error response is suggested to be text or html but not otherwise
        specified. Intended to provide useful information for debugging.
505178
def as_txt(self):
        
        s = "IIIF Image Server Error\n\n"
        s += self.text if (self.text) else 'UNKNOWN_ERROR'
        s += "\n\n"
        if (self.parameter):
            s += "parameter=%s\n" % self.parameter
        if (self.code):
            s += "code=%d\n\n" % self.code
        for header in sorted(self.headers):
            s += "header %s=%s\n" % (header, self.headers[header])
        return s
1294200
function (err, data) {
      debug(`${service}.${method} response:`, err || {
        status: data && data.status,
        size: data && JSON.stringify(data).length
      });
      if (err) return next(err.cause || err);

      res.data = data;

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'create') {
        res.status(statusCodes.created);
      }

      return next();
    }
273189
def data_response(self):
        
        d = self.ImageNumerics.image2array(self.Data.data * self.ImageNumerics.mask)
        return d
81920
protected function renderError() {	
	    $error = I18N::translate('The media file was not found in this family tree.');

    	$width  = (mb_strlen($error) * 6.5 + 50) * 1.15;
    	$height = 60;
    	$im     = imagecreatetruecolor($width, $height); /* Create a black image */
    	$bgc    = imagecolorallocate($im, 255, 255, 255); /* set background color */
    	imagefilledrectangle($im, 2, 2, $width - 4, $height - 4, $bgc); /* create a rectangle, leaving 2 px border */
    
    	$this->embedText($im, $error, 100, '255, 0, 0', WT_ROOT . Config::FONT_DEJAVU_SANS_TTF, 'top', 'left');
    
    	http_response_code(404);
    	header('Content-Type: image/png');
    	imagepng($im);
    	imagedestroy($im);
	}
760696
def error_response(message, status=400, code=None):
    """""""
    from django.http import JsonResponse
    data = {'message': message}
    if code:
        data['code'] = code
    LOG.error("Error response, status code is : {} | {}".format(status, data))
    return JsonResponse(data=data, status=status)
568886
def err_response(reqid, code, msg, data=None):
    
    err = { "code": code, "message": msg }
    if data:
        err["data"] = data
    return { "jsonrpc": "2.0", "id": reqid, "error": err }
275844
@Override
	public void render() {
		String text = this.getErrorContent();
		if(isHtml){
			Response.setStatus(getErrorCode());
			new HtmlView(text).render();
		}else{
			super.render();
		}
	}
920051
def _render_image(self, spec, container_args, alt_text=None):
        

        try:
            path, image_args, title = image.parse_image_spec(spec)
        except Exception as err:  # pylint: disable=broad-except
            logger.exception("Got error on spec %s: %s", spec, err)
            return ('<span class="error">Couldn\'t parse image spec: ' +
                    '<code>{}</code> {}</span>'.format(flask.escape(spec),
                                                       flask.escape(str(err))))

        composite_args = {**container_args, **image_args}

        try:
            img = image.get_image(path, self._search_path)
        except Exception as err:  # pylint: disable=broad-except
            logger.exception("Got error on image %s: %s", path, err)
            return ('<span class="error">Error loading image {}: {}</span>'.format(
                flask.escape(spec), flask.escape(str(err))))

        return img.get_img_tag(title, alt_text, **composite_args)
883160
function Request_handleError(response) {
        var request, code, that = this;

        if (this.isRendered) {
            // we have multiple recursion in parse for catching
            return false;
        }
        // log error request
        logger.error('Request:', {
            url: this.url,
            status: this.statusCode,
            id: this.id,
            isRendered: this.isRendered,
            content_type: this.getHeader('content-type'),
            message: response
        });

        if (response instanceof Error) {
            response = error.silentHttpError(500, {}, 'SlientHttpError: mvcjs error is not thrown', response);
        }
        // get error code from message
        code = getErrorCode(response);
        // set status codes
        this.setStatusCode(code);
        // stop current chain!!!
        this.stopPromiseChain();

        response += '\n';
        response += 'ROUTE:' + core.inspect(this._getRouteInfo());

        if (!this.isERROR && !!router.getErrorRoute()) {
            // return new request
            this.isRendered = true;

            request = new Request({
                request: this.request,
                response: this.response,
                isForwarded: true,
                body: this.body,
                isERROR: true
            }, router.createUrl(router.getErrorRoute()));
            // pass exception response over parsed url query as query parameter
            // assign to exception
            request.parsedUrl.query.exception = response;
            // set status codes for new request
            request.setStatusCode(code);
            // return parsed request
            return request.parse();
        } else {
            this.addHeader('Content-Type', 'text/plain');
            return response;
        }
    }
95351
function (err, req, res, next) {
    err = this.coerceError(err);

    if (err instanceof errors.NotFound && req.accepts('html')) {
      if (err instanceof errors.BinNotFound) {
        if (req.editor) {
          return (new BinHandler(this.sandbox)).notFound(req, res, next);
        }
      }

      return this.renderErrorPage('error', err, req, res);
    } else if (err instanceof errors.HTTPError) {
      // return this.renderError(err, req, res);
      return this.renderErrorPage(err.status, err, req, res);
    }

    if (err) {
      // console.error(err.stack);
    }

    next(err);
  }
718271
def error(self, status_code, request, message=None):
        
        status_code_text = HTTP_STATUS_CODES.get(status_code, 'http error')
        status_error_tag = status_code_text.lower().replace(' ', '_')
        custom_response_map = {
            404: self.make_error_response(
                status_error_tag,
                'The requested URL {} was not found on this service.'.format(
                    request.path
                )
            ),
            400: self.make_error_response(status_error_tag, message),
            405: self.make_error_response(
                status_error_tag,
                'The requested URL {} was not allowed HTTP method {}.'.format(
                    request.path, request.method
                )
            ),
        }
        return self._raw_response(
            status_code,
            custom_response_map.get(
                status_code,
                self.make_error_response(
                    status_error_tag, message or status_code_text
                )
            )
        )
480977
def render_to_response(self, context, **response_kwargs):
        
        filename = os.path.basename(self.object.file.name)

        # Try to guess the content type of the given file
        content_type, _ = mimetypes.guess_type(self.object.file.name)
        if not content_type:
            content_type = 'text/plain'

        response = HttpResponse(self.object.file, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename={}'.format(filename)

        return response
771266
def parse_image_response(self, response):
        
        if 'xml' in response.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        obj = self._response_object_from_header(
            obj_head_dict=response.headers,
            content=response.content)
        return obj
641090
function NexmoErrorStatus(response) {
  MessagingServiceStatus.call(this, 'nexmo');

  // There was an error when attempting to send message
  this.state.message = response.messages[0].status + ': ' + response.messages[0]['error-text'];

  // See https://docs.nexmo.com/index.php/sms-api/send-message#response_code for details
  var statusCode = parseInt(response.messages[0].status);
  if (statusCode == 1) this.state.code = this.StatusCodes.LIMIT_EXCEEDED;
  else if (statusCode == 2) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 3) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 4) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 5) this.state.code = this.StatusCodes.SERVICE_DOWN;
  else if (statusCode == 6) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 7) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 8) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 9) this.state.code = this.StatusCodes.LIMIT_EXCEEDED;
  else if (statusCode == 11) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 12) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 13) this.state.code = this.StatusCodes.SERVICE_DOWN;
  else if (statusCode == 14) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 15) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 16) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 19) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (statusCode == 20) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (statusCode == 29) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
924347
def displayResponse(request, openid_response):
    
    s = getServer(request)

    # Encode the response into something that is renderable.
    try:
        webresponse = s.encodeResponse(openid_response)
    except EncodingError, why:
        # If it couldn't be encoded, display an error.
        text = why.response.encodeToKVForm()
        return direct_to_template(
            request,
            'server/endpoint.html',
            {'error': cgi.escape(text)})

    # Construct the appropriate django framework response.
    r = http.HttpResponse(webresponse.body)
    r.status_code = webresponse.code

    for header, value in webresponse.headers.iteritems():
        r[header] = value

    return r
657217
def httperror_handler(error):
    
    status_code = error.status_code or 500
    output = {
        'code': status_code,
        'message': error.body or UNEXPECTED_ERROR,
        'reason': bottle.HTTP_CODES.get(status_code) or None,
    }
    if bottle.DEBUG:
        LOG.warning("Debug-mode server is returning traceback and error "
                    "details in the response with a %s status.",
                    error.status_code)
        if error.exception:
            output['exception'] = repr(error.exception)
        else:
            if any(sys.exc_info()):
                output['exception'] = repr(sys.exc_info()[1])
            else:
                output['exception'] = None

        if error.traceback:
            output['traceback'] = error.traceback
        else:
            if any(sys.exc_info()):
                # Otherwise, format_exc() returns "None\n"
                # which is pretty silly.
                output['traceback'] = traceback.format_exc()
            else:
                output['traceback'] = None

    # overwrite previous body attr with json
    if isinstance(output['message'], bytes):
        output['message'] = output['message'].decode(
            'utf-8', errors='replace')

    # Default type and writer to json.
    accept = bottle.request.get_header('accept') or 'application/json'
    writer = functools.partial(
        json.dumps, sort_keys=True, indent=4)
    error.set_header('Content-Type', 'application/json')
    if 'json' not in accept:
        if 'yaml' in accept:
            if not yaml:
                LOG.warning("Yaml requested but pyyaml is not installed.")
            else:
                error.set_header('Content-Type', 'application/x-yaml')
                writer = functools.partial(
                    yaml.safe_dump,
                    default_flow_style=False,
                    indent=4)
            # html could be added here.

    error.body = [writer(output).encode('utf8')]
    return error.body
710900
function renderIssue(message) {
	return issueTemplate({
		severity: severityString(message.severity),
		severityName: message.severity === 1 ? 'Warning' : 'Error',
		lineNumber: message.line,
		column: message.column,
		message: message.message,
		ruleId: message.ruleId,
		ruleLink: getRuleLink(message.ruleId)
	});
}