Created
November 3, 2016 08:32
-
-
Save tpapp/6f67ff36a228f47a1792e011d9b0fc13 to your computer and use it in GitHub Desktop.
looking for simpler solution: how to report context for an error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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