Formats a ParseException into an error message suitable for
displaying on a web page
420156
static String formatParseException(String pExpressionString,
                                       ParseException pExc) {
        // Generate the String of expected tokens
        StringBuffer expectedBuf = new StringBuffer();
        int maxSize = 0;
        boolean printedOne = false;

        if (pExc.expectedTokenSequences == null) {
            return pExc.toString();
        }

        for (int i = 0; i < pExc.expectedTokenSequences.length; i++) {
            if (maxSize < pExc.expectedTokenSequences[i].length) {
                maxSize = pExc.expectedTokenSequences[i].length;
            }
            for (int j = 0; j < pExc.expectedTokenSequences[i].length; j++) {
                if (printedOne) {
                    expectedBuf.append(", ");
                }
                expectedBuf.append
                        (pExc.tokenImage[pExc.expectedTokenSequences[i][j]]);
                printedOne = true;
            }
        }
        String expected = expectedBuf.toString();

        // Generate the String of encountered tokens
        StringBuffer encounteredBuf = new StringBuffer();
        Token tok = pExc.currentToken.next;
        for (int i = 0; i < maxSize; i++) {
            if (i != 0) {
                encounteredBuf.append(" ");
            }
            if (tok.kind == 0) {
                encounteredBuf.append(pExc.tokenImage[0]);
                break;
            }
            encounteredBuf.append(addEscapes(tok.image));
            tok = tok.next;
        }
        String encountered = encounteredBuf.toString();

        // Format the error message
        return MessageFormat.format
                (Constants.PARSE_EXCEPTION,
                        new Object[]{
                                expected,
                                encountered,
                        });
    }
1356044
def error(self, amplexception):
        
        msg = '\t'+str(amplexception).replace('\n', '\n\t')
        print('Error:\n{:s}'.format(msg))
        raise amplexception
1057240
def FormatProblem(self, d=None):
    
    if not d:
      d = self.GetDictToFormat()

    output_error_text = self.__class__.ERROR_TEXT % d
    if ('reason' in d) and d['reason']:
      return '%s\n%s' % (output_error_text, d['reason'])
    else:
      return output_error_text
462801
private synchronized String printTargetError( Throwable t ) {
            StringBuilder msgs = new StringBuilder(t.toString());
            while ( null != (t = t.getCause()) )
                msgs.append("\n").append(t.toString());
            return msgs.toString();
    }
163959
def compose_error_message(http_response, max_len=200)
        msg = http_response.body.gsub("\n", ' ')
        msg = "#{msg[0..max_len]} ..." if msg.size > max_len
        msg
      end
576265
private JsonParserException createParseException(Exception e, String message, boolean tokenPos) {
    if (tokenPos)
      return new JsonParserException(e, message + " on line " + tokenLinePos + ", char " + tokenCharPos,
          tokenLinePos, tokenCharPos, tokenCharOffset);
    else {
      int charPos = Math.max(1, index - rowPos - utf8adjust);
      return new JsonParserException(e, message + " on line " + linePos + ", char " + charPos, linePos, charPos,
          index + charOffset);
    }
  }
1085995
def format_errors(errors):
        

        def _get_message(node):
            """
            Get the message to display in the error output.
            """
            messages = set()

            try:
                messages.update([node['message']])
            except KeyError:
                pass

            for check_group in ['any', 'all', 'none']:
                try:
                    for check in node[check_group]:
                        messages.update([check.get('message')])
                except KeyError:
                    pass

            messages = messages.difference([''])
            return '; '.join(messages)

        lines = []
        for error_type in errors:
            lines.append(u"Severity: {}".format(error_type.get("impact")))
            lines.append(u"Rule ID: {}".format(error_type.get("id")))
            lines.append(u"Help URL: {}\n".format(error_type.get('helpUrl')))

            for node in error_type['nodes']:
                msg = u"Message: {}".format(_get_message(node))
                html = u"Html: {}".format(node.get('html').encode('utf-8'))
                target = u"Target: {}".format(node.get('target'))
                fill_opts = {
                    'width': 100,
                    'initial_indent': '\t',
                    'subsequent_indent': '\t\t',
                }
                lines.append(fill(msg, **fill_opts))
                lines.append(fill(html, **fill_opts))
                lines.append(fill(target, **fill_opts))
                lines.append('\n')

        return '\n'.join(lines)
1145942
function getLoggableErrorMessage(error: Error): string | void {
  let result = chalk.red.bold('Error: ');

  if (error instanceof errorTypes.ConfigFatalError) {
    result += 'Fatal configuration error.\n\n';
    result += `${error.message}\n`;
    return result;
  }

  if (error instanceof errorTypes.ConfigValidationError) {
    result += 'Invalid configuration.\n\n';
    if (error.messages) {
      error.messages.forEach((m) => {
        result += `- ${m}\n`;
      });
    } else {
      result += `${error.message}\n`;
    }
    return result;
  }

  if (error instanceof errorTypes.WebpackFatalError) {
    const webpackOptions = [
      'webpackLoaders',
      'webpackPlugins',
      'webpackStaticIgnore'
    ]
      .map((x) => chalk.yellow(x))
      .join(', ');
    result += `Webpack fatal error. Please check any Batfish configuration options that pass directly into Webpack configuration (${webpackOptions}).\n\n`;
    result += `Error message: ${error.originalError.message}\n`;
    return result;
  }

  if (error instanceof errorTypes.WebpackCompilationError) {
    result += `Webpack compilation error.\n\n`;
    const formattedMessages = webpackFormatMessages(error.stats);
    formattedMessages.errors.forEach((errorMessage) => {
      result += `${errorMessage}\n`;
    });
    return result;
  }

  if (error instanceof errorTypes.CssCompilationError) {
    result += `CSS compilation error. This may mean you have non-standard syntax that you forgot to compile with PostCSS.\n\n`;
    result += `${error.message}\n`;
    return result;
  }

  if (error instanceof errorTypes.WebpackNodeParseError) {
    result += `Failed to parse Webpack-compiled version of static-render-pages.js\n\n`;
    result += `Error message: ${error.originalError.message}\n\n`;
    result += renderPrettyErrorStack(error.originalError);
    return result;
  }

  if (error instanceof errorTypes.WebpackNodeExecutionError) {
    result += `Failed to execute Webpack-compiled version of static-render-pages.js.\n\n${chalk.bold.yellow(
      'You may be importing a JS file that cannot run in Node.'
    )}\n\n`;
    result += renderPrettyErrorStack(error.originalError);
    return result;
  }

  if (error instanceof errorTypes.FrontMatterError) {
    result += `Failed to parse front matter in ${chalk.yellow(
      path.relative(process.cwd(), error.filePath)
    )}.\n\n`;
    if (error.originalError.name === 'YAMLException') {
      result += `YAML error: ${error.originalError.reason}\n\n`;
      result += codeFrame.codeFrameColumns(
        error.originalError.mark.buffer,
        {
          start: {
            line: error.originalError.mark.line + 1,
            column: error.originalError.mark.column
          }
        },
        { highlightCode: true, linesAbove: 10, linesBelow: 10 }
      );
    } else {
      result += renderPrettyErrorStack(error.originalError);
    }
    return result;
  }

  return;
}
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);
    }
  }
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)
498250
@Override
    @GwtIncompatible("incompatible method")
    public String getFormattedExceptionMessage(final String baseMessage){
        final StringBuilder buffer = new StringBuilder(256);
        if (baseMessage != null) {
            buffer.append(baseMessage);
        }

        if (contextValues.size() > 0) {
            if (buffer.length() > 0) {
                buffer.append('\n');
            }
            buffer.append("Exception Context:\n");

            int i = 0;
            for (final Pair<String, Object> pair : contextValues) {
                buffer.append("\t[");
                buffer.append(++i);
                buffer.append(':');
                buffer.append(pair.getKey());
                buffer.append("=");
                final Object value = pair.getValue();
                if (value == null) {
                    buffer.append("null");
                } else {
                    String valueStr;
                    try {
                        valueStr = value.toString();
                    } catch (final Exception e) {
                        valueStr = "Exception thrown on toString(): " + ExceptionUtils.getStackTrace(e);
                    }
                    buffer.append(valueStr);
                }
                buffer.append("]\n");
            }
            buffer.append("---------------------------------");
        }
        return buffer.toString();
    }
803341
function formatWebErrors(errors) {
    let errs = {};
    if (errors && errors.constructor == Array) {
        errors.forEach(function(item) {
            if (!errs[item.param]) errs[item.param] = [];
            errs[item.param].push(item.msg);
        });
    }
    return errs;
}
129044
function(opts = {}) {
  if (opts.handleUncaughtExceptions == null) {
    opts.handleUncaughtExceptions = true;
  }
  if (opts.structuredStackTrace == null) {
    opts.structuredStackTrace = false;
  }
  if (opts.handleUncaughtExceptions) {
    process.on('uncaughtException', function(err) {
      prettyPrint(err, {
        colorize: process.stdout.isTTY
      });
      return process.exit(1);
    });
  }
  return Error.prepareStackTrace = function(err, stack) {
    var _stack, frame;
    _stack = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = stack.length; i < len; i++) {
        frame = stack[i];
        results.push(wrap(err, frame));
      }
      return results;
    })();
    if (opts.structuredStackTrace) {
      err.structuredStackTrace = structured(err, stack);
    }
    return err + ((function() {
      var i, len, results;
      results = [];
      for (i = 0, len = _stack.length; i < len; i++) {
        frame = _stack[i];
        results.push('\n    at ' + frame);
      }
      return results;
    })()).join('');
  };
}
577071
@Override
    public String displayError(String pathPrefix) {

        if (pathPrefix == null) {
            pathPrefix = "";
        }
        StringBuffer html = new StringBuffer(512);
        html.append("<table border='0' cellpadding='5' cellspacing='0' style='width: 100%; height: 100%;'>");
        html.append("\t<tr>");
        html.append("\t\t<td style='vertical-align: middle; height: 100%;'>");
        html.append(getHtmlPart("C_BLOCK_START", "Error"));
        html.append("\t\t\t<table border='0' cellpadding='0' cellspacing='0' style='width: 100%;'>");
        html.append("\t\t\t\t<tr>");
        html.append("\t\t\t\t\t<td><img src='").append(pathPrefix).append("resources/error.png' border='0'></td>");
        html.append("\t\t\t\t\t<td>&nbsp;&nbsp;</td>");
        html.append("\t\t\t\t\t<td style='width: 100%;'>");
        html.append("\t\t\t\t\t\tThe Alkacon OpenCms update wizard has not been started correctly!<br>");
        html.append("\t\t\t\t\t\tPlease click <a href='").append(pathPrefix);
        html.append("index.jsp'>here</a> to restart the wizard.");
        html.append("\t\t\t\t\t</td>");
        html.append("\t\t\t\t</tr>");
        html.append("\t\t\t</table>");
        html.append(getHtmlPart("C_BLOCK_END"));
        html.append("\t\t</td>");
        html.append("\t</tr>");
        html.append("</table>");
        return html.toString();
    }
275269
function throwError(token, messageFormat) {
        var error,
            args = Array.prototype.slice.call(arguments, 2),
            msg = messageFormat.replace(
                /%(\d)/g,
                function (whole, index) {
                    assert(index < args.length, 'Message reference must be in range');
                    return args[index];
                }
            );

        error = new Error(msg);
        error.index = index;
        error.description = msg;
        throw error;
    }
63921
private String printError(Throwable t) {

        StringBuffer result = new StringBuffer(1024);
        result.append("/*\n");
        result.append(CmsStringUtil.escapeHtml(t.getMessage()));
        result.append("\n*/\n");
        result.append("function init() {\n");
        result.append("}\n");
        return result.toString();
    }
837504
def parseErrorAndResponse(self, data):
        """"""

        xml = fromstring(data)
        error = xml.find('.//ERROR')

        if error is None:
            self.deferred.callback(self.parseResponse(xml))
            return

        try:
            code = int(error.attrib['CODE'])
        except ValueError:
            code = 0

        self.deferred.errback(CIMError(code, error.attrib['DESCRIPTION']))