[IMP] compiler: improve error message when failing to compile template

Previously, when a template failed to compile because of a syntax error
(typically because we don't do any syntax checking when compiling
expression, allowing invalid expressions to be transpiled successfully),
the error reporting was very minimal: you would only get the error
message itself (eg: "Unexpected token") with the stack information of
the error pointing to the call to `new Function` in owl, which is not
very useful.

This commit catches the compilation error and completes it with
information about the template name when available, and also adds the
generated code to the error message, allowing the user to just
copy/paste it in their web console or code editor to get a more precise
location for the error.
This commit is contained in:
Samuel Degueldre
2023-07-20 09:38:40 +02:00
committed by Géry Debongnie
parent 7bc9d34a64
commit 9d99f8936b
5 changed files with 103 additions and 2 deletions
+12 -1
View File
@@ -2,6 +2,7 @@ import type { TemplateSet } from "../runtime/template_set";
import type { BDom } from "../runtime/blockdom";
import { CodeGenerator, Config } from "./code_generator";
import { parse } from "./parser";
import { OwlError } from "../runtime";
export type Template = (context: any, vnode: any, key?: string) => BDom;
@@ -27,5 +28,15 @@ export function compile(
const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
const code = codeGenerator.generateCode();
// template function
return new Function("app, bdom, helpers", code) as TemplateFunction;
try {
return new Function("app, bdom, helpers", code) as TemplateFunction;
} catch (originalError: any) {
const { name } = options;
const nameStr = name ? `template "${name}"` : "anonymous template";
const err = new OwlError(
`Failed to compile ${nameStr}: ${originalError.message}\n\ngenerated code:\nfunction(app, bdom, helpers) {\n${code}\n}`
);
err.cause = originalError;
throw err;
}
}