From 0beb4a4793a05557cfb0a32f94c41616606efced Mon Sep 17 00:00:00 2001 From: Tristan Hume Date: Mon, 19 Aug 2013 15:45:05 -0400 Subject: [PATCH] Add handy context to strict parser error messages. --- lib/liquid/tag.rb | 12 ++++++++++-- lib/liquid/variable.rb | 3 +++ test/liquid/error_handling_test.rb | 14 +++++++++++++- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lib/liquid/tag.rb b/lib/liquid/tag.rb index 9a354d4..ce0df63 100644 --- a/lib/liquid/tag.rb +++ b/lib/liquid/tag.rb @@ -35,11 +35,11 @@ module Liquid def parse_with_selected_parser(markup) case @options[:error_mode] || Template.error_mode - when :strict then strict_parse(markup) + when :strict then strict_parse_with_error_context(markup) when :lax then lax_parse(markup) when :warn begin - return strict_parse(markup) + return strict_parse_with_error_context(markup) rescue SyntaxError => e @warnings ||= [] @warnings << e @@ -47,5 +47,13 @@ module Liquid end end end + + private + def strict_parse_with_error_context(markup) + strict_parse(markup) + rescue SyntaxError => e + e.message << " in \"#{markup.strip}\"" + raise e + end end # Tag end # Liquid diff --git a/lib/liquid/variable.rb b/lib/liquid/variable.rb index 20cb022..7aa2999 100644 --- a/lib/liquid/variable.rb +++ b/lib/liquid/variable.rb @@ -70,6 +70,9 @@ module Liquid @filters << [filtername, filterargs] end p.consume(:end_of_string) + rescue SyntaxError => e + e.message << " in \"{{#{markup}}}\"" + raise e end def parse_filterargs(p) diff --git a/test/liquid/error_handling_test.rb b/test/liquid/error_handling_test.rb index 6e4889a..80902a3 100644 --- a/test/liquid/error_handling_test.rb +++ b/test/liquid/error_handling_test.rb @@ -79,11 +79,23 @@ class ErrorHandlingTest < Test::Unit::TestCase end end + def test_strict_error_messages + err = assert_raise(SyntaxError) do + Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', :error_mode => :strict) + end + assert_equal 'Unexpected character = in "1 =! 2"', err.message + + err = assert_raise(SyntaxError) do + Liquid::Template.parse('{{%%%}}', :error_mode => :strict) + end + assert_equal 'Unexpected character % in "{{%%%}}"', err.message + end + def test_warnings template = Liquid::Template.parse('{% if ~~~ %}derp{% else %}wat{% endif %}', :error_mode => :warn) assert_equal 'wat', template.render assert_equal 1, template.errors.size - assert_equal 'Unexpected character ~.', template.errors.first.message + assert_equal 'Unexpected character ~ in "~~~"', template.errors.first.message end # Liquid should not catch Exceptions that are not subclasses of StandardError, like Interrupt and NoMemoryError