Skip to content
Prev Previous commit
Next Next commit
Wrap unicode error as syntax error
  • Loading branch information
moreal committed Aug 13, 2022
commit 714ce4d07d7c900e7ceb2dab9eae725f15f749e4
14 changes: 11 additions & 3 deletions vm/src/stdlib/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,17 @@ mod builtins {
}
}

Ok(Either::A(
vm.ctx.new_str(std::str::from_utf8(source).unwrap()),
))
match std::str::from_utf8(source) {
Ok(s) => Ok(Either::A(vm.ctx.new_str(s))),
Err(err) => {
let msg = format!(
"(unicode error) 'utf-8' codec can't decode byte 0x{:x?} in position {}: invalid start byte",
source[err.valid_up_to()],
err.valid_up_to()
);
Err(vm.new_exception_msg(vm.ctx.exceptions.syntax_error.to_owned(), msg))
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to handle error first not to disturb to read main control flow

Suggested change
match std::str::from_utf8(source) {
Ok(s) => Ok(Either::A(vm.ctx.new_str(s))),
Err(err) => {
let msg = format!(
"(unicode error) 'utf-8' codec can't decode byte 0x{:x?} in position {}: invalid start byte",
source[err.valid_up_to()],
err.valid_up_to()
);
Err(vm.new_exception_msg(vm.ctx.exceptions.syntax_error.to_owned(), msg))
}
let source = std::str::from_utf8(source).map_err(|err| {
let msg = format!(
"(unicode error) 'utf-8' codec can't decode byte 0x{:x?} in position {}: invalid start byte",
source[err.valid_up_to()],
err.valid_up_to()
);
Err(vm.new_exception_msg(vm.ctx.exceptions.syntax_error.to_owned(), msg))
})?;
Either::A(vm.ctx.new_str(s))),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I applied it in c672d8f.

}
}
Either::B(code) => Ok(Either::B(code)),
}?;
Expand Down