angu
angu copied to clipboard
Helper to return user-friendly errors?
Just wondering, what's the best way to return user-friendly errors? The errors are a bit cryptic and sometimes even deeply nested in recursive structures.
For example, this is not enough:
const getErrorLine = (expr, start, end) => {
let text = expr.slice(start, start + end + 8) || 'char 0';
return text;
};
const raiseError = (expr, res) => {
let err = res.value;
if (err.kind === 'EVAL_THROW') {
throw new Error(`The code evaluation threw an error`);
} else if (
err.kind === 'FUNCTION_NOT_DEFINED' ||
err.kind === 'NOT_A_FUNCTION'
) {
throw new Error(`Function not defined`);
} else if (err.pos?.start !== undefined && err.pos?.end !== undefined) {
let text = getErrorLine(expr, err.pos.start, err.pos.end);
throw new Error(
`The code has syntax errors or invalid variable names near: ${text}`
);
} else {
throw new Error(`The code has syntax errors.`);
}
};
Because for EVAL_THROW
, the error is sometimes nested like this:
