Render the exception (debug)

Returns a [title, html] tuple.
421331
protected function doRenderDebug(\Throwable $exception, ?string $outputBuffer = null): array
    {
        $title = Exception::getName($exception);
        $extras = '';

        $this->emit(WebErrorScreenEvents::RENDER_DEBUG, [
            'title' => &$title,
            'extras' => &$extras,
            'exception' => $exception,
            'output_buffer' => $outputBuffer,
        ]);

        $output = '';
        $chain = Exception::getChain($exception);
        $totalExceptions = count($chain);

        for ($i = 0; $i < $totalExceptions; ++$i) {
            $output .= $this->renderException($chain[$i], $i, $totalExceptions);

            if ($i === 0) {
                // render extras after the first exception
                $output .= $extras;
                $output .= $this->renderOutputBuffer($outputBuffer);
                $output .= $this->renderPlaintextTrace($exception);
            }
        }

        return [$title, $output];
    }
1313257
def get(self, request, *args, **kwargs):
        """"""
        try:
            kwargs = self.load_object(kwargs)
        except Exception as e:
            return self.render_te_response({
                'title': str(e),
            })

        if not self.has_permission(request):
            return self.render_te_response({
                'title': 'No access',
            })
        return self.render_te_response(self.display_dialog(*args, **kwargs))
722329
final ParseErrorDetails renderError() {
    final int errorIndex = toIndex(currentErrorAt);
    final String encounteredName = getEncountered();
    final ArrayList<String> errorStrings = Lists.arrayList(errors.size());
    for (Object error : errors) {
      errorStrings.add(String.valueOf(error));
    }
    switch (currentErrorType) {
    case UNEXPECTED :
      return new EmptyParseError(errorIndex, encounteredName) {
        @Override public String getUnexpected() {
          return errorStrings.get(0);
        }
      };
    case FAILURE :
      return new EmptyParseError(errorIndex, encounteredName) {
        @Override public String getFailureMessage() {
          return errorStrings.get(0);
        }
      };
    case EXPECTING:
    case MISSING:
    case DELIMITING:
      return new EmptyParseError(errorIndex, encounteredName) {
        @Override public List<String> getExpected() {
          return errorStrings;
        }
      };
    default:
      return new EmptyParseError(errorIndex, encounteredName);
    }
  }
626635
protected function renderHtmlExceptionOrError($exception)
    {
        if (!$exception instanceof Exception && !$exception instanceof \Error) {
            throw new RuntimeException("Unexpected type. Expected Exception or Error.");
        }

        $html = sprintf('<div><strong>Type:</strong> %s</div>', get_class($exception));

        if (($code = $exception->getCode())) {
            $html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
        }

        if (($message = $exception->getMessage())) {
            $html .= sprintf('<div><strong>Message:</strong> %s</div>', htmlentities($message));
        }

        if (($file = $exception->getFile())) {
            $html .= sprintf('<div><strong>File:</strong> %s</div>', $file);
        }

        if (($line = $exception->getLine())) {
            $html .= sprintf('<div><strong>Line:</strong> %s</div>', $line);
        }

        if (($trace = $exception->getTraceAsString())) {
            $html .= '<h2>Trace</h2>';
            $html .= sprintf('<pre>%s</pre>', htmlentities($trace));
        }

        return $html;
    }
753263
def render_view(parser, token):
    
    bits = token.split_contents()

    n = len(bits)
    if n < 2:
        raise TemplateSyntaxError("'%s' takes at least one view as argument")

    viewname = bits[1]

    kwargs = {}
    if n > 2:
        for bit in bits[2:]:
            match = kwarg_re.match(bit)
            if not match:
                raise TemplateSyntaxError("Malformed arguments to render_view tag")
            name, value = match.groups()
            if name:
                kwargs[name] = parser.compile_filter(value)

    return StringNode(viewname, kwargs)
154612
def render_error_page(code, exc, mimetype='text/html', traceback=''):
    
    from giotto.views import get_jinja_template

    if 'json' in mimetype:
        return json.dumps({
            'code': code,
            'exception': exc.__class__.__name__,
            'message': str(exc),
        })

    et = get_config('error_template')
    if not et:
        return "%s %s\n%s" % (code, str(exc), traceback)
    template = get_jinja_template(et)
    return template.render(
        code=code,
        exception=exc.__class__.__name__,
        message=str(exc),
        traceback=traceback
    )
1115983
@Override
    protected void renderTagEnd() {
        try {
            if (StringUtils.isNotEmpty(this.output)) {
                this.output = toString(this.escape
                        ? escape(this.output)
                        : this.output);
                JspWriter writer = this.pageContext.getOut();
                boolean renderTag = renderTag()
                        && (StringUtils.isNotBlank(this.tagName) || StringUtils.isNotBlank(getClasses()));
                if (renderTag) {
                    super.renderTagStart();
                }
                writer.write(this.output);
                if (renderTag) {
                    super.renderTagEnd();
                }
            }
        } catch (IOException ioex) {
            LOG.error(ioex.getMessage(), ioex);
        }
    }
1333343
def render_summary(self, app, include_title=True):
        """"""
        title = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = text_('Syntax Error')
            else:
                title = text_('Traceback <small>(most recent call last)'
                              '</small>')

        for frame in self.frames:
            txt = frame.info
            if not txt:
                txt = text_(' title="%s"' % escape(frame.info))
            if not txt:
                txt = text_('')
            frames.append(
                text_('<li%s>%s') % (txt, frame.render()))

        if self.is_syntax_error:
            description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
        else:
            description_wrapper = text_('<blockquote>%s</blockquote>')
        vars = {
            'classes': text_(' '.join(classes)),
            'title': title and text_('<h3 class="traceback">%s</h3>'
                                     % title) or text_(''),
            'frames': text_('\n'.join(frames)),
            'description': description_wrapper % escape(self.exception),
        }
        return render('exception_summary.jinja2', app, vars)
1161150
def render_exception_js(self, exception):
        

        from .http import JsonResponse

        response = {}
        response["error"] = exception.error
        response["error_description"] = exception.reason

        return JsonResponse(response, status=getattr(exception, 'code', 400))
494888
public static function render(Exception $exception, $return = false)
    {
        $attributes = self::$config['error_report_attrs'];
    
        $html = '<div ' . $attributes['atomik-error'] . '>'
           . '<span ' . $attributes['atomik-error-title'] . '>' 
           . $exception->getMessage() . '</span>'
           . '<br />An error of type <strong>' . get_class($exception) . '</strong> '
           . 'was caught at <strong>line ' . $exception->getLine() . '</strong><br />'
           . 'in file <strong>' . $exception->getFile() . '</strong>'
           . '<p>' . $exception->getMessage() . '</p>'
           . '<table ' . $attributes['atomik-error-lines'] . '>';
        
        // builds the table which display the lines around the error
        $lines = file($exception->getFile());
        $start = $exception->getLine() - 7;
        $start = $start < 0 ? 0 : $start;
        $end = $exception->getLine() + 7;
        $end = $end > count($lines) ? count($lines) : $end; 
        for($i = $start; $i < $end; $i++) {
            // color the line with the error. with standard Exception, lines are
            if($i == $exception->getLine() - (get_class($exception) != 'ErrorException' ? 1 : 0)) {
                $html .= '<tr ' . $attributes['atomik-error-line-error'] . '><td>';
            }
            else {
                $html .= '<tr ' . $attributes['atomik-error-line'] . '>'
                       . '<td ' . $attributes['atomik-error-line-number'] . '>';
            }
            $html .= $i . '</td><td ' . $attributes['atomik-error-line-text'] . '>' 
                   . (isset($lines[$i]) ? htmlspecialchars($lines[$i]) : '') . '</td></tr>';
        }
        
        $html .= '</table>'
               . '<strong>Stack:</strong><p ' . $attributes['atomik-error-stack'] . '>' 
               . nl2br($exception->getTraceAsString())
               . '</p></div>';
        
        return $html;
    }
522131
protected function renderException($exception)
  {
    if ($this->myDebug)
    {
      if ($exception instanceof ErrorException)
      {
        $message = $exception->getName();
      }
      elseif ($exception instanceof NamedException)
      {
        $message = "Exception ({$exception->getName()})";
      }
      else
      {
        $message = 'Exception';
      }

      $message .= " '".get_class($exception)."'";
      $message .= ' with message '.$exception->getMessage();
      $message .= "\n\n";
      $message .= "in ".$exception->getFile().':'.$exception->getLine()."\n";
      $message .= "\n";
      $message .= "Stack trace:\n";
      $message .= $exception->getTraceAsString();
    }
    elseif ($exception instanceof NamedException)
    {
      $message = $exception->getName().': '.$exception->getMessage();
    }
    else
    {
      $message = 'Error: '.$exception->getMessage();
    }

    echo $message, "\n";
  }
93122
def render_html(self, request, instance, context):
        
        render_template = self.get_render_template(request, instance, email_format='html')
        if not render_template:
            return str(u"{No HTML rendering defined for class '%s'}" % self.__class__.__name__)

        instance_context = self.get_context(request, instance, email_format='html', parent_context=context)
        instance_context['email_format'] = 'html'

        html = self.render_to_string(request, render_template, instance_context)
        if self.render_replace_context_fields:
            html = replace_fields(html, instance_context)  # pass safe-string
        return html
284708
def render(self, tmpl_name, request_env):
        
        return super(WebApplication, self).render(tmpl_name, request_env)
379343
function render_stack_trace(error, { markup_settings, log })
{
	// Supports custom `html` for an error
	if (error.html)
	{
		return { response_status: error.status, response_body: error.html }
	}

	// Handle `superagent` errors
	// https://github.com/visionmedia/superagent/blob/29ca1fc938b974c6623d9040a044e39dfb272fed/lib/node/response.js#L106
	if (error.response && typeof error.status === 'number')
	{
		// If the `superagent` http request returned an HTML response 
		// (possibly an error stack trace),
		// then just output that stack trace.
		if (error.response.headers['content-type']
			&& error.response.headers['content-type'].split(';')[0].trim() === 'text/html')
		{
			return { response_status: error.status, response_body: error.message }
		}
	}

	// If this error has a stack trace then it can be shown

	let stack_trace

	if (error.stack)
	{
		stack_trace = error.stack
	}
	// `superagent` errors have the `original` property 
	// for storing the initial error
	else if (error.original && error.original.stack)
	{
		stack_trace = error.original.stack
	}

	// If this error doesn't have a stack trace - do nothing
	if (!stack_trace)
	{
		return {}
	}

	// Render the error's stack trace as HTML markup
	try
	{
		return { response_body: html_stack_trace({ stack: stack_trace }, markup_settings) }
	}
	catch (error)
	{
		log.error(error)

		// If error stack trace couldn't be rendered as HTML markup,
		// then just output it as plain text.
		return { response_body: error.stack }
	}
}
350645
def format_html_exception(*args):
        

        escape = lambda x: foundations.strings.replace(x,
                                                       OrderedDict([("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")]))
        format = lambda x: foundations.strings.replace(x.expandtabs(8),
                                                       OrderedDict(
                                                           [("\n\n", "\n \n"), ("\n\n", "\n \n"), (" ", "&nbsp;"),
                                                            ("\n", "<br/>\n")]))

        verbose = 10
        cls, instance, trcback = args
        stack = foundations.exceptions.extract_stack(foundations.exceptions.get_inner_most_frame(trcback), verbose)

        python = "Python {0}: {1}".format(sys.version.split()[0], sys.executable)
        date = time.ctime(time.time())

        html = []
        html.append(
            "<div class=\"header\"><span class=\"floatRight textAlignRight\"><h4>{0}<br/>{1}</h4></span><h2>{2}</h2></div>".format(
                python, date, escape(foundations.strings.to_string(cls))))

        html.append("<div class=\"traceback\">")
        for line in foundations.exceptions.format_exception(cls, instance, trcback):
            html.append("{0}<br/>".format(format(escape(line))))
        html.append("</div>")

        html.append("<div class=\"content\">")
        html.append("<p>An unhandled exception occured in <b>{0} {1}</b>! \
                Sequence of calls leading up to the exception, in their occurring order:</p>".format(
            Constants.application_name, Constants.version))
        html.append("<br/>")
        html.append("<div class=\"stack\">")
        for frame, file_name, line_number, name, context, index in stack:
            location = "<b>{0}{1}</b>".format(escape(name) if name != "<module>" else "",
                                              inspect.formatargvalues(*inspect.getargvalues(frame)))
            html.append(
                "<div class=\"location\">File <a href=file://{0}>\"{0}\"</a>, line <b>{1}</b>, in {2}</div><br>".format(
                    file_name, line_number, location))
            html.append("<div class=\"context\">")
            for i, line in enumerate(context):
                if i == index:
                    html.append("<span class=\"highlight\">{0}&nbsp;{1}</span>".format(
                        line_number - index + i, format(line)))
                else:
                    html.append("{0}&nbsp;{1}".format(line_number - index + i, format(line)))
            html.append("</div>")
            html.append("<br/>")
        html.append("</div>")
        html.append("</div>")
        html.append("<div class=\"exception\">")
        for line in traceback.format_exception_only(cls, instance):
            html.append("<b>{0}</b>".format(format(line)))
        html.append("</div>")

        html.append("<div class=\"debug\">")
        html.append("<p>Frames locals by stack ordering, innermost last:</p>")
        for frame, locals in foundations.exceptions.extract_locals(trcback):
            name, file_name, line_number = frame
            html.append(
                "<div class=\"frame\">Frame \"{0}\" in <a href=file://{1}>\"{1}\"</a> file, line <b>{2}</b>:</div>".format(
                    escape(name), file_name, line_number))
            html.append("<br/>")
            html.append("<div class=\"locals\">")
            arguments, nameless_args, keyword_args, locals = locals
            has_arguments, has_locals = any((arguments, nameless_args, keyword_args)), any(locals)
            has_arguments and html.append("<div class=\"cls\"><b>{0}</b></div><ul>".format("Arguments:"))
            for key, value in arguments.iteritems():
                html.append("<li><b>{0}</b> = {1}</li>".format(key, escape(value)))
            for value in nameless_args:
                html.append("<li><b>{0}</b></li>".format(escape(value)))
            for key, value in sorted(keyword_args.iteritems()):
                html.append("<li><b>{0}</b> = {1}</li>".format(key, escape(value)))
            has_arguments and html.append("</ul>")
            has_locals and html.append("<div class=\"cls\"><b>{0}</b></div><ul>".format("Locals:"))
            for key, value in sorted(locals.iteritems()):
                html.append("<li><b>{0}</b> = {1}</li>".format(key, escape(value)))
            has_locals and html.append("</ul>")
            html.append("</div>")
            html.append("<br/>")
        html.append("</div>")

        return "".join(html)
1316244
public function render()
    {
        $exception_context = array(
            'type'=> get_called_class(),
            'code'=> $this->getCode(),
            'message'=>$this->getMessage(),
            'line'=>$this->getLine(),
            'file'=>$this->getFile(),
        );
        $this->webservices->log(
            $this->webservices->getOption('error_log_mask'), $exception_context, Logger::ERROR
        );
        $this->webservices->getResponse()
            ->addContent('error', $exception_context);
        $this->webservices->display();
    }
1322796
def render(self):
        """"""
        return FRAME_HTML % {
            'id': self.id,
            'filename': escape(self.filename),
            'lineno': self.lineno,
            'function_name': escape(self.function_name),
            'current_line': escape(self.current_line.strip())
        }