Skip to content

Commit 370ee73

Browse files
committed
handle lexer errors by throwing exception instead of ignoring
1 parent 505aa81 commit 370ee73

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/main/java/graphql/parser/Parser.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@
22

33
import graphql.Internal;
44
import graphql.language.Document;
5+
import graphql.language.SourceLocation;
56
import graphql.parser.antlr.GraphqlLexer;
67
import graphql.parser.antlr.GraphqlParser;
8+
import org.antlr.v4.runtime.BaseErrorListener;
79
import org.antlr.v4.runtime.CharStreams;
810
import org.antlr.v4.runtime.CodePointCharStream;
911
import org.antlr.v4.runtime.CommonTokenStream;
12+
import org.antlr.v4.runtime.RecognitionException;
13+
import org.antlr.v4.runtime.Recognizer;
1014
import org.antlr.v4.runtime.Token;
1115
import org.antlr.v4.runtime.atn.PredictionMode;
1216

@@ -51,6 +55,13 @@ public Document parseDocument(Reader reader) throws InvalidSyntaxException {
5155
}
5256

5357
GraphqlLexer lexer = new GraphqlLexer(charStream);
58+
lexer.removeErrorListeners();
59+
lexer.addErrorListener(new BaseErrorListener() {
60+
@Override
61+
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
62+
throw new InvalidSyntaxException(new SourceLocation(line, charPositionInLine), "Invalid syntax: " + msg, null, null, null);
63+
}
64+
});
5465

5566
CommonTokenStream tokens = new CommonTokenStream(lexer);
5667

src/test/groovy/graphql/parser/ParserTest.groovy

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -733,4 +733,19 @@ triple3 : """edge cases \\""" "" " \\"" \\" edge cases"""
733733
fragmentDefinition.name == "Foo"
734734

735735
}
736+
737+
def "parser should throw syntax errors"() {
738+
given:
739+
def input = """
740+
type Foo {
741+
name / String
742+
}
743+
"""
744+
when:
745+
def document = Parser.parse(input)
746+
println document
747+
then:
748+
def e = thrown(InvalidSyntaxException)
749+
e.message.contains("Invalid syntax")
750+
}
736751
}

0 commit comments

Comments
 (0)