Rust Error Handling: Replacing panic! and unwrap With Result

https://hackernoon.imgix.net/images/2jqChkrv03exBUgkLrDzIbfM99q2-j6821v7.jpeg

In this post, we are going to learn about error handling in Rust. Once we cover all the concepts, we will build a TOML config parser with schema validation. Every error must be handled properly using Result. Let's start.

You can get the source code from here

Why panic! and unwrap Are Not Enough

In the previous articles, we used panic! and .expect() and .unwrap() all over the place. When something went wrong, we just crashed the program. Let me remind you:

In the JSON parser, when the lexer hit an unexpected character, we did this:

panic!("Unexpected character: {}", c as char);

And when the parser encountered a token it didn't expect:

panic!("Expected ':' in object");

This is fine for a learning exercise. But real software can't just crash when something goes wrong. A web server can't crash because one request had bad input, it needs to return an...

Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE