Rust handles errors in a bit unusual way (at least compared to other languages). Functions that may have an error return a Result value. Result may either contain a value or an error. We can do many things to get the value out of it.
For example, if the function that called the erroring functions also returns a compatible Result, we can propagate the possible error and return with it early.
let value = result?; // Return with the error if it contains an error
Or we can provide a default value:
let value = result.unwrap_or(default_value); // We will get default_value if result contains an error
Or, the often problematic way, unwrap returns the value if it's all ok - and panics if the result contains an error. A panic crashes the current thread.
let value = result.unwrap();
The code sample is bad, because it is passing user input to a function that could fail and calling unwrap on it - therefore, a malicious user could pass an invalid value, crashing the program.
let name: String = urlencoding::decode(&name).unwrap(); // TODO: this is probably a DoS vulnerability
let (mut sock_tx: SplitSink<WebSocket, Message>, mut sock_rx: SplitStream<WebSocket>) = ws.split();
let (tx: UnboundedSender<Message>, mut rx: UnboundedReceiver<Message>) = mpsc::unbounded_channel();
let user: User = User {
name,
tx: tx.clone(),
current_room_id: None,
}
2
u/[deleted] Aug 07 '21
i am learning rust myself could anyone explain why this is bad?
5
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Aug 05 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
2
u/Voltra_Neo Aug 09 '21
I was wondering what's wrong until I realized this is user input and you don't propagate the error