This structure is what Django wants when errors occur in templates.
    It gives the user a nice stack trace in the error page during debug.
195073
def get_template_debug(template_name, error):
    '''
    
    '''
    # This is taken from mako.exceptions.html_error_template(), which has an issue
    # in Py3 where files get loaded as bytes but `lines = src.split('\n')` below
    # splits with a string. Not sure if this is a bug or if I'm missing something,
    # but doing a custom debugging template allows a workaround as well as a custom
    # DMP look.
    # I used to have a file in the templates directory for this, but too many users
    # reported TemplateNotFound errors. This function is a bit of a hack, but it only
    # happens during development (and mako.exceptions does this same thing).
    #   /justification
    stacktrace_template = MakoTemplate(r"""
<%! from mako.exceptions import syntax_highlight, pygments_html_formatter %>
<style>
    .stacktrace { margin:5px 5px 5px 5px; }
    .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
    .nonhighlight { padding:0px; background-color:#DFDFDF; }
    .sample { padding:10px; margin:10px 10px 10px 10px;
                font-family:monospace; }
    .sampleline { padding:0px 10px 0px 10px; }
    .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
    .location { font-size:80%; }
    .highlight { white-space:pre; }
    .sampleline { white-space:pre; }

    % if pygments_html_formatter:
        ${pygments_html_formatter.get_style_defs() | n}
        .linenos { min-width: 2.5em; text-align: right; }
        pre { margin: 0; }
        .syntax-highlighted { padding: 0 10px; }
        .syntax-highlightedtable { border-spacing: 1px; }
        .nonhighlight { border-top: 1px solid #DFDFDF;
                        border-bottom: 1px solid #DFDFDF; }
        .stacktrace .nonhighlight { margin: 5px 15px 10px; }
        .sourceline { margin: 0 0; font-family:monospace; }
        .code { background-color: #F8F8F8; width: 100%; }
        .error .code { background-color: #FFBDBD; }
        .error .syntax-highlighted { background-color: #FFBDBD; }
    % endif

    ## adjustments to Django css
    table.source {
        background-color: #fdfdfd;
    }
    table.source > tbody > tr > th {
        width: auto;
    }
    table.source > tbody > tr > td {
        font-family: inherit;
        white-space: normal;
        padding: 15px;
    }
    #template {
        background-color: #b3daff;
    }

</style>
<%

    src = tback.source
    line = tback.lineno
    if isinstance(src, bytes):
        src = src.decode()
    if src:
        lines = src.split('\n')
    else:
        lines = None
%>
<h3>${tback.errorname}: ${tback.message}</h3>

% if lines:
    <div class="sample">
    <div class="nonhighlight">
    % for index in range(max(0, line-4),min(len(lines), line+5)):
        <%
        if pygments_html_formatter:
            pygments_html_formatter.linenostart = index + 1
        %>
        % if index + 1 == line:
        <%
        if pygments_html_formatter:
            old_cssclass = pygments_html_formatter.cssclass
            pygments_html_formatter.cssclass = 'error ' + old_cssclass
        %>
            ${lines[index] | n,syntax_highlight(language='mako')}
        <%
        if pygments_html_formatter:
            pygments_html_formatter.cssclass = old_cssclass
        %>
        % else:
            ${lines[index] | n,syntax_highlight(language='mako')}
        % endif
    % endfor
    </div>
    </div>
% endif

<div class="stacktrace">
% for (filename, lineno, function, line) in tback.reverse_traceback:
    <div class="location">${filename}, line ${lineno}:</div>
    <div class="nonhighlight">
    <%
       if pygments_html_formatter:
           pygments_html_formatter.linenostart = lineno
    %>
        <div class="sourceline">${line | n,syntax_highlight(filename)}</div>
    </div>
% endfor
</div>
""")
    tback = RichTraceback(error, error.__traceback__)
    lines = stacktrace_template.render_unicode(tback=tback)
    return {
        'message': '',
        'source_lines': [
            ( '', mark_safe(lines) ),
        ],
        'before': '',
        'during': '',
        'after': '',
        'top': 0,
        'bottom': 0,
        'total': 0,
        'line': tback.lineno or 0,
        'name': template_name,
        'start': 0,
        'end': 0,
    }
571316
function onError(message, error) {
  // log the stack trace
  util.print_debug_error(error);

  // update error message
  try {
    error.message = message + ': ' + error.message;
  } catch(e) {}

  throw error;
}
584944
function renderTemplate(template, context) {
			try {
				var func = _.template(template.template);
				return func(context);
			}
			catch (e) {
				grunt.fail.fatal('Error while rendering template ' + template.filename + ': ' + e.message);
			}
		}
756029
def _render_errors(field):
    
    template = '{0}/layout/field_errors.html'.format(appsettings.CRISPY_TEMPLATE_PACK)
    return render_to_string(template, {
        'field': field,
        'form_show_errors': True,
    })
319128
def error(request, message, extra_tags='', fail_silently=False, async=False):
    """"""
    if ASYNC and async:
        messages.debug(_get_user(request), message)
    else:
        add_message(request, constants.ERROR, message, extra_tags=extra_tags,
                    fail_silently=fail_silently)
1074346
function callsites() {
	var _ = Error.prepareStackTrace;
	Error.prepareStackTrace = function (_, stack) {
		return stack;
	};
	var stack = new Error().stack.slice(1);
	Error.prepareStackTrace = _;
	return stack;
}
999052
def _on_error_page_write_error(self, status_code, **kwargs):
        """"""

        if oz.settings.get('debug'):
            exception_type, exception_value, tback = sys.exc_info()
            is_breakpoint = isinstance(exception_value, oz.error_pages.DebugBreakException)

            frames = oz.error_pages.get_frames(tback, is_breakpoint)
            frames.reverse()

            if is_breakpoint:
                exception_type = 'Debug breakpoint'
                exception_value = ''

            self.render(oz.settings["error_pages_template"],
                exception_type=exception_type,
                exception_value=exception_value,
                frames=frames,
                request_input=self.request.body,
                request_cookies=self.cookies,
                request_headers=self.request.headers,
                request_path=self.request.uri,
                request_method=self.request.method,
                response_output="".join(self._write_buffer),
                response_headers=self._headers,
                prettify_object=oz.error_pages.prettify_object,
            )

            return oz.break_trigger
561381
public function resolveErrorTemplate()
    {
        $this->buildTemplateIndex();

        $template = (array_key_exists(self::ERROR_TEMPLATE, $this->templateIndex)) ?
            $this->templateIndex[self::ERROR_TEMPLATE] :
            false;

        return($template);
    }
1369080
def debug(self, *args) -> "Err":
        
        error = self._create_err("debug", *args)
        print(self._errmsg(error))
        return error
918344
def msg(cls, error=None, debug=True, trace=True):
        
        if debug and error is not None:
            print(error)
        # TODO: BUG: trace should only be printed if debug is true
        if trace:
            print(traceback.format_exc())
588463
def generate_crash_handler_decorator(error_decorator=None):
    """"""

    def crash_handler(f):
        """Return a decorator that reports failed api calls via the error_reporter,
        for use on every server endpoint"""

        @wraps(f)
        def wrapper(*args, **kwargs):
            """Generate a report of this api call, and if the call failed or was too slow,
            forward this report via the error_reporter"""

            data = {}
            t0 = timenow()
            exception_string = ''

            # Call endpoint and log execution time
            try:
                res = f(*args, **kwargs)
            except Exception as e:
                # An unhandled exception occured!
                exception_string = str(e)
                exc_type, exc_value, exc_traceback = sys.exc_info()
                trace = traceback.format_exception(exc_type, exc_value, exc_traceback, 30)
                data['trace'] = trace

                # If it is a PyMacaronException, just call its http_reply()
                if hasattr(e, 'http_reply'):
                    res = e.http_reply()
                else:
                    # Otherwise, forge a Response
                    e = UnhandledServerError(exception_string)
                    log.error("UNHANDLED EXCEPTION: %s" % '\n'.join(trace))
                    res = e.http_reply()

            t1 = timenow()

            # Is the response an Error instance?
            response_type = type(res).__name__
            status_code = 200
            is_an_error = 0
            error = ''
            error_description = ''
            error_user_message = ''

            error_id = ''

            if isinstance(res, Response):
                # Got a flask.Response object
                res_data = None

                status_code = str(res.status_code)

                if str(status_code) == '200':

                    # It could be any valid json response, but it could also be an Error model
                    # that pymacaron_core handled as a status 200 because it does not know of
                    # pymacaron Errors
                    if res.content_type == 'application/json':
                        s = str(res.data)
                        if '"error":' in s and '"error_description":' in s and '"status":' in s:
                            # This looks like an error, let's decode it
                            res_data = res.get_data()
                else:
                    # Assuming it is a PyMacaronException.http_reply()
                    res_data = res.get_data()

                if res_data:
                    if type(res_data) is bytes:
                        res_data = res_data.decode("utf-8")

                    is_json = True
                    try:
                        j = json.loads(res_data)
                    except ValueError as e:
                        # This was a plain html response. Fake an error
                        is_json = False
                        j = {'error': res_data, 'status': status_code}

                    # Make sure that the response gets the same status as the PyMacaron Error it contained
                    status_code = j['status']
                    res.status_code = int(status_code)

                    # Patch Response to contain a unique id
                    if is_json:
                        if 'error_id' not in j:
                            # If the error is forwarded by multiple micro-services, we
                            # want the error_id to be set only on the original error
                            error_id = str(uuid.uuid4())
                            j['error_id'] = error_id
                            res.set_data(json.dumps(j))

                        if error_decorator:
                            # Apply error_decorator, if any defined
                            res.set_data(json.dumps(error_decorator(j)))

                    # And extract data from this error
                    error = j.get('error', 'NO_ERROR_IN_JSON')
                    error_description = j.get('error_description', res_data)
                    if error_description == '':
                        error_description = res_data

                    if not exception_string:
                        exception_string = error_description

                    error_user_message = j.get('user_message', '')
                    is_an_error = 1


            request_args = []
            if len(args):
                request_args.append(args)
            if kwargs:
                request_args.append(kwargs)

            data.update({
                # Set only on the original error, not on forwarded ones, not on
                # success responses
                'error_id': error_id,

                # Call results
                'time': {
                    'start': t0.isoformat(),
                    'end': t1.isoformat(),
                    'microsecs': (t1.timestamp() - t0.timestamp()) * 1000000,
                },

                # Response details
                'response': {
                    'type': response_type,
                    'status': str(status_code),
                    'is_error': is_an_error,
                    'error_code': error,
                    'error_description': error_description,
                    'user_message': error_user_message,
                },

                # Request details
                'request': {
                    'params': pformat(request_args),
                },
            })

            populate_error_report(data)

            # inspect may raise a UnicodeDecodeError...
            fname = function_name(f)

            #
            # Should we report this call?
            #

            # If it is an internal errors, report it
            if data['response']['status'] and int(data['response']['status']) >= 500:
                report_error(
                    title="%s(): %s" % (fname, exception_string),
                    data=data,
                    is_fatal=True
                )

            log.info("")
            log.info(" <= Done!")
            log.info("")

            return res

        return wrapper

    return crash_handler
783928
function (args) {
        var div = args.cfg.tplDiv;

        if (div) {
            aria.utils.Dom.replaceHTML(div, "#TEMPLATE ERROR#");
        }
        this.$callback(args.cb, {
            success : false
        });
    }
1327039
def render_report_error(self, request, error, status):
        

        opts = self.model._meta
        app_label = opts.app_label
        request.current_app = self.admin_site.name
        context = dict(
            self.admin_site.each_context(request),
            module_name=force_text(opts.verbose_name_plural),
            title=(_('Tracking report error for %s') % force_text(opts.verbose_name)),
            opts=opts, app_label=app_label, error=error
        )

        return TemplateResponse(request, self.report_error_template or [
            "admin/{}/{}/tracking_report_error.html".format(app_label, opts.model_name),
            "admin/{}/tracking_report_error.html".format(app_label),
            "admin/tracking_report_error.html"
        ], context, status=status)
1255102
def render_exception(error):
    
    _, _, category = str.partition(request.path, '/')

    qsize = index.queue_length()
    if isinstance(error, http_error.NotFound) and qsize:
        response = flask.make_response(render_error(
            category, "Site reindex in progress (qs={})".format(qsize), 503))
        response.headers['Retry-After'] = qsize
        response.headers['Refresh'] = max(5, qsize / 5)
        return response, 503

    if isinstance(error, http_error.HTTPException):
        return render_error(category, error.name, error.code, exception={
            'type': type(error).__name__,
            'str': error.description,
            'args': error.args
        })

    return render_error(category, "Exception occurred", 500, exception={
        'type': type(error).__name__,
        'str': str(error),
        'args': error.args
    })
514565
def get_traceback_html(self, **kwargs):
        ""
        t = Template(TECHNICAL_500_TEMPLATE)
        c = self.get_traceback_data()
        c['kwargs'] = kwargs
        return t.render(Context(c))
55517
def page_not_found(request, template_name='404.html'):
    
    response = render_in_page(request, template_name)

    if response:
        return response

    template = Template(
        '<h1>Not Found</h1>'
        '<p>The requested URL {{ request_path }} was not found on this server.</p>')
    body = template.render(RequestContext(
        request, {'request_path': request.path}))
    return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE)
819482
def write_error(self, status_code, **kwargs):
        
        reason = self._reason

        if self.settings.get("serve_traceback") and "exc_info" in kwargs:
            error = []
            for line in traceback.format_exception(*kwargs["exc_info"]):
                error.append(line)
        else:
            error = None
        data = {'_traceback': error, 'message': reason, 'code': status_code}
        content = self.render_exception(**data)
        self.write(content)