Skip to content

Commit

Permalink
liluat.render: pretty error messages for runtime errors
Browse files Browse the repository at this point in the history
  • Loading branch information
FSMaxB committed Mar 26, 2016
1 parent ee35c4c commit 670d37f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
13 changes: 12 additions & 1 deletion liluat.lua
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,18 @@ function liluat.render(t, env)

-- compile and run the lua code
local render_function = sandbox(t.code, t.name, env)
render_function()
local status, error_message = pcall(render_function)
if not status then
local line_number, message = error_message:match(":(%d+):(.*)")
-- lines before and after the error
local lines = string_lines(t.code, line_number - 3, line_number + 3)
error(
'Runtime error in sandboxed code "' .. t.name .. '" in line ' .. line_number .. ':\n'
.. message .. '\n\n'
.. prepend_line_numbers(lines, line_number - 3, line_number),
2
)
end

return table.concat(result)
end
Expand Down
35 changes: 35 additions & 0 deletions spec/liluat_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1318,4 +1318,39 @@ __liluat_output_function("more text")]]
assert.equal("1.1.2", liluat.version())
end)
end)

describe("liluat.render", function ()
it("should handle runtime errors and print its surrounding lines", function ()
local code = [[
-- 1
-- 2
-- 3
-- 4
-- 5
-- 6
local test = "a" .. nil
-- 8
-- 9
-- 10
-- 11
-- 12
-- 13]]

local expected = [[
Runtime error in sandboxed code "code" in line 7:
.*
4: %-%- 4
5: %-%- 5
6: %-%- 6
7:> local test = "a" .. nil
8: %-%- 8
9: %-%- 9
10: %-%- 10]]

local status, error_message = pcall(liluat.render, {name = 'code', code = code})

assert.is_false(status)
assert.truthy(error_message:find(expected))
end)
end)
end)

0 comments on commit 670d37f

Please sign in to comment.