Skip to content

Commit 6ff86e9

Browse files
committed
Improve error reporting of invalid UTF-8 when deserializing strings
std::io::Read read_to_string() [1] reports this uninformative error: thread 'main' panicked at 'Err: IOError(Custom { kind: InvalidData, error: StringError("stream did not contain valid UTF-8") })', src/server/mod.rs:442:33 Instead of read_to_string(), use read_to_end() to read into a buffer, then convert using String::from_utf8() and unwrap it. This gives a better error message when UTF-8 fails to decode: thread '' panicked at 'called Result::unwrap() on an Err value: FromUtf8Error { bytes: [105, 110, 101, 99, 114, 97, 102, 116, 58, 99, 114, 97, 102, 116, 105, 110, 103, 95, 115, 104, 97, 112, 101, 100, 20, 109, 105, 110, 101, 99, 114, 97, 102, 116, 58, 98, 111, 110, 101, 95, 98, 108, 111, 99, 107, 3, 3, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 1, 134, 5, 1, 0, 1, 249, 2, 1, 0, 25, 109], error: Utf8Error { valid_up_to: 50, error_len: Some(1) } }', src/libcore/result.rs:1009:5 which is helpful for tracking down protocol errors, such as updating to a new protocol (developed for GH-132 / GH-72). [1] https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_string [2] https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8
1 parent 703d120 commit 6ff86e9

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

protocol/mod.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,8 +257,9 @@ impl Serializable for String {
257257
let len = VarInt::read_from(buf)?.0;
258258
debug_assert!(len >= 0, "Negative string length: {}", len);
259259
debug_assert!(len <= 65536, "String length too big: {}", len);
260-
let mut ret = String::new();
261-
buf.take(len as u64).read_to_string(&mut ret)?;
260+
let mut bytes = Vec::<u8>::new();
261+
buf.take(len as u64).read_to_end(&mut bytes)?;
262+
let ret = String::from_utf8(bytes).unwrap();
262263
Result::Ok(ret)
263264
}
264265
fn write_to<W: io::Write>(&self, buf: &mut W) -> Result<(), Error> {

0 commit comments

Comments
 (0)