add custom errors to encoding lib (#9513)

pull/9536/head
Atakan Yenel 2021-03-30 14:27:26 +02:00 committed by GitHub
parent 5c21c748c9
commit ab6e0ed0b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 13 deletions

View File

@ -6,12 +6,25 @@ module csv
// Once interfaces are further along the idea would be to have something similar to
// go's io.reader & bufio.reader rather than reading the whole file into string, this
// would then satisfy that interface. I designed it this way to be easily adapted.
const (
err_comment_is_delim = error('encoding.csv: comment cannot be the same as delimiter')
err_invalid_delim = error('encoding.csv: invalid delimiter')
err_eof = error('encoding.csv: end of file')
err_invalid_le = error('encoding.csv: could not find any valid line endings')
)
struct ErrCommentIsDelimiter {
msg string = 'encoding.csv: comment cannot be the same as delimiter'
code int
}
struct ErrInvalidDelimiter {
msg string = 'encoding.csv: invalid delimiter'
code int
}
struct ErrEndOfFile {
msg string = 'encoding.csv: end of file'
code int
}
struct ErrInvalidLineEnding {
msg string = 'encoding.csv: could not find any valid line endings'
code int
}
struct Reader {
// not used yet
@ -59,7 +72,7 @@ pub fn (mut r Reader) read() ?[]string {
fn (mut r Reader) read_line() ?string {
// last record
if r.row_pos == r.data.len {
return csv.err_eof
return IError(&ErrEndOfFile{})
}
le := if r.is_mac_pre_osx_le { '\r' } else { '\n' }
mut i := r.data.index_after(le, r.row_pos)
@ -71,7 +84,7 @@ fn (mut r Reader) read_line() ?string {
r.is_mac_pre_osx_le = true
} else {
// no valid line endings found
return csv.err_invalid_le
return IError(&ErrInvalidLineEnding{})
}
} else {
// No line ending on file
@ -89,10 +102,10 @@ fn (mut r Reader) read_line() ?string {
fn (mut r Reader) read_record() ?[]string {
if r.delimiter == r.comment {
return csv.err_comment_is_delim
return IError(&ErrCommentIsDelimiter{})
}
if !valid_delim(r.delimiter) {
return csv.err_invalid_delim
return IError(&ErrInvalidDelimiter{})
}
mut need_read := true
mut keep_raw := false
@ -154,7 +167,7 @@ fn (mut r Reader) read_record() ?[]string {
}
}
if i <= -1 && fields.len == 0 {
return csv.err_invalid_delim
return IError(&ErrInvalidDelimiter{})
}
}
return fields

View File

@ -23,7 +23,7 @@ pub fn new_writer() &Writer {
// write writes a single record
pub fn (mut w Writer) write(record []string) ?bool {
if !valid_delim(w.delimiter) {
return err_invalid_delim
return IError(&ErrInvalidDelimiter{})
}
le := if w.use_crlf { '\r\n' } else { '\n' }
for n, field_ in record {