Skip to content

Instantly share code, notes, and snippets.

@tpapp
Created November 3, 2016 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpapp/6f67ff36a228f47a1792e011d9b0fc13 to your computer and use it in GitHub Desktop.
Save tpapp/6f67ff36a228f47a1792e011d9b0fc13 to your computer and use it in GitHub Desktop.
looking for simpler solution: how to report context for an error
type ParseErrorLoc
T
string
column
line
end
function Base.show(io::IO, pel::ParseErrorLoc)
print("could not parse \"$(pel.string)\" as $(pel.T)")
if pel.column > 0
print(" in column $(pel.column)")
if pel.line > 0
print(" in line $(pel.line)")
end
end
println()
end
function parsefield{T <: Real}(::Type{T}, string)
try parse(T, string)
catch e
if isa(e, ArgumentError)
throw(ParseErrorLoc(T, string, -1, -1))
else
rethrow(e)
end
end
end
function parserow(schema, strings)
function parse_handling_error(T, string, column)
try parsefield(T, string)
catch e
if isa(e, ParseErrorLoc)
e.column = column
end
rethrow(e)
end
end
[parse_handling_error(T, string, column)
for (column, (T, string)) in enumerate(zip(schema, strings))]
end
function parsefile(io, schema)
line = 1
while !eof(io)
strings = split(chomp(readline(io)), ';')
try parserow(schema, strings)
catch e
if isa(e, ParseErrorLoc)
e.line = line
end
rethrow(e)
end
line += 1
end
end
test_file = """
1;2;3
4;5;6
7;error;9
"""
parsefile(IOBuffer(test_file), fill(Int, 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment