You can do this by implementing the antlr4.error.ErrorListener
interface and providing one of the interface methods such as syntaxError
to be invoked upon each error.
class ExprErrorListener extends antlr4.error.ErrorListener {
syntaxError(recognizer, offendingSymbol, line, column, msg, err) {
...
}
}
Disable the default error listener and enable the custom listener with:
parser.removeErrorListeners();
parser.addErrorListener(new ExprErrorListener());
Note that you can skip the class and pass in an object with the syntaxError
function available. Here's a minimal, complete example on the Expr.g4
grammar:
const antlr4 = require("antlr4");
const {ExprLexer} = require("./parser/ExprLexer");
const {ExprParser} = require("./parser/ExprParser");
const expression = "2 + 8 * 9 - \n";
const input = new antlr4.InputStream(expression);
const lexer = new ExprLexer(input);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new ExprParser(tokens);
parser.buildParseTrees = true;
parser.removeErrorListeners();
parser.addErrorListener({
syntaxError: (recognizer, offendingSymbol, line, column, msg, err) => {
console.error(`${offendingSymbol} line ${line}, col ${column}: ${msg}`);
}
});
const tree = parser.prog();
Gives:
[@6,12:12='\n',<10>,1:12] line 1, col 12: mismatched input '\n' expecting {'(', ID, INT}
See also error handlers.