Stop throwing ParseError when throwOnError is false (#1169)

* Stop throwing ParseError when throwOnError is false

`render`, `renderToString`, etc. now catch ParseError and render it to the
raw LaTeX (with proper escaping) and a hover title with the error.

Along the way:
* Use new `katex.__renderToDomTree` in katex-spec's `_getBuilt`.
  (This was necessary to get the new error handling in `_getBuilt`.)
* Fix jest results which must always be functions, not strings.

* fix lint

* Fix flow error

Leave error type unspecified, as we check it with instanceof.

* Update katex-spec.js
This commit is contained in:
Erik Demaine
2018-05-09 09:18:50 -04:00
committed by ylemkimon
parent 3e529dd5a0
commit 49e673a59c
4 changed files with 94 additions and 15 deletions

View File

@@ -13,6 +13,8 @@ import Settings from "./src/Settings";
import { buildTree, buildHTMLTree } from "./src/buildTree";
import parseTree from "./src/parseTree";
import buildCommon from "./src/buildCommon";
import domTree from "./src/domTree";
import utils from "./src/utils";
import type {SettingsOptions} from "./src/Settings";
@@ -72,6 +74,26 @@ const generateParseTree = function(
return parseTree(expression, settings);
};
/**
* If the given error is a KaTeX ParseError and options.throwOnError is false,
* renders the invalid LaTeX as a span with hover title giving the KaTeX
* error message. Otherwise, simply throws the error.
*/
const renderError = function(
error,
expression: string,
options: Settings,
) {
if (options.throwOnError || !(error instanceof ParseError)) {
throw error;
}
const node = buildCommon.makeSpan(["katex-error"],
[new domTree.symbolNode(expression)]);
node.setAttribute("title", error.toString());
node.setAttribute("style", `color:${options.errorColor}`);
return node;
};
/**
* Generates and returns the katex build tree. This is used for advanced
* use cases (like rendering to custom output).
@@ -81,8 +103,12 @@ const renderToDomTree = function(
options: SettingsOptions,
) {
const settings = new Settings(options);
const tree = parseTree(expression, settings);
return buildTree(tree, expression, settings);
try {
const tree = parseTree(expression, settings);
return buildTree(tree, expression, settings);
} catch (error) {
return renderError(error, expression, settings);
}
};
/**
@@ -94,8 +120,12 @@ const renderToHTMLTree = function(
options: SettingsOptions,
) {
const settings = new Settings(options);
const tree = parseTree(expression, settings);
return buildHTMLTree(tree, expression, settings);
try {
const tree = parseTree(expression, settings);
return buildHTMLTree(tree, expression, settings);
} catch (error) {
return renderError(error, expression, settings);
}
};
export default {