feature: Allow a default exception renderer to be specified (#837)

This could be used to preserve the old default of rendering
non-Liquid::Error messages or for providing default behaviour like error
reporting which could be missed if the exception renderer needed to be
specified on each render.
This commit is contained in:
Dylan Thacker-Smith
2016-12-12 10:29:09 -05:00
committed by GitHub
parent fae3a2de7b
commit 869dbc7ebf
3 changed files with 21 additions and 3 deletions

View File

@@ -27,6 +27,7 @@ module Liquid
@this_stack_used = false
self.exception_renderer = Template.default_exception_renderer
if rethrow_errors
self.exception_renderer = ->(e) { raise }
end
@@ -78,9 +79,7 @@ module Liquid
e.template_name ||= template_name
e.line_number ||= line_number
errors.push(e)
e = exception_renderer.call(e) if exception_renderer
e.to_s
exception_renderer.call(e).to_s
end
def invoke(method, *args)

View File

@@ -69,6 +69,11 @@ module Liquid
# :error raises an error when tainted output is used
attr_writer :taint_mode
attr_accessor :default_exception_renderer
Template.default_exception_renderer = lambda do |exception|
exception
end
def file_system
@@file_system
end

View File

@@ -211,6 +211,20 @@ class ErrorHandlingTest < Minitest::Test
assert_equal [Liquid::InternalError], template.errors.map(&:class)
end
def test_setting_default_exception_renderer
old_exception_renderer = Liquid::Template.default_exception_renderer
exceptions = []
Liquid::Template.default_exception_renderer = ->(e) { exceptions << e; '' }
template = Liquid::Template.parse('This is a runtime error: {{ errors.argument_error }}')
output = template.render({ 'errors' => ErrorDrop.new })
assert_equal 'This is a runtime error: ', output
assert_equal [Liquid::ArgumentError], template.errors.map(&:class)
ensure
Liquid::Template.default_exception_renderer = old_exception_renderer if old_exception_renderer
end
def test_exception_renderer_exposing_non_liquid_error
template = Liquid::Template.parse('This is a runtime error: {{ errors.runtime_error }}', line_numbers: true)
exceptions = []