Simple error handling in Rust

  Рет қаралды 31,052

Let's Get Rusty

Let's Get Rusty

Күн бұрын

In today's video, we are talking about error handling in Rust with error-stack.
Code: github.com/letsgetrusty/error...
Blog post: hash.dev/blog/announcing-erro...
Timestamps:
0:00 Intro
0:54 error-stack Origins
3:19 Example Overview
7:40 Adding Error Handling
23:09 Outro
#rust #programming #tutorial

Пікірлер: 86
@letsgetrusty
@letsgetrusty 2 жыл бұрын
📝Get your *FREE Rust cheat sheet* : www.letsgetrusty.com/cheatsheet
@derekwan
@derekwan 2 жыл бұрын
This video is superb - you’ve demonstrated the problem, and then the solution’s superiority. Almost a video which can serve as a good selling point for Rust!
@vabka-7708
@vabka-7708 Жыл бұрын
This problem simply solved with exceptions in other languages :) But Rust's solution is better
@warever9999
@warever9999 Жыл бұрын
@@vabka-7708 In other languages you can ignore exceptions and this can lead to a buggy code. Rust strives for correctness
@vabka-7708
@vabka-7708 Жыл бұрын
@@warever9999 this is exactly what i said.
@DrIngo1980
@DrIngo1980 2 жыл бұрын
Thanks Bogdan for showcasing the "error-stack" error handling crate/library. Very cool stuff. And I applaud you for the effort you went through to show how this can really be used to make a dev's life easier when debugging programs out in the wild! Just set the logging level accordingly and you'd get enough info to pin-point an a problematic code path/etc. 👍👍👍! Honestly, there is about 20+ software development KZfaq channels I have subscribed to, but yours is in the TOP 3 to watch for sure (no questions asked!)!!! Especially if one is interested or working with Rust. You are doing a banger of a job here! Thank you! 👍👍👍
@stevetaylor4990
@stevetaylor4990 Жыл бұрын
What are the other two?
@SyamaMishra
@SyamaMishra 2 жыл бұрын
I'd love more videos on error handling, especially details on the structural problems the error group are solving.
@jddecarlo
@jddecarlo 2 жыл бұрын
Seems like an awesome crate! Thanks for bringing it to our attention!
@MattiaProcopio
@MattiaProcopio 2 жыл бұрын
How to have a better day? It's Friday and a new LGR video 🎉
@Codeaholic1
@Codeaholic1 2 жыл бұрын
This looks compelling. I hope the ergonomics are improved a bit. It's a little verbose as is.
@lizzyfleckenstein9837
@lizzyfleckenstein9837 Жыл бұрын
When you are debugging, you mostly want verbosity. You just dont want to throw a lot of verbose messages at the user.
@Codeaholic1
@Codeaholic1 Жыл бұрын
@@lizzyfleckenstein9837 I meant the method names and code to setup the errors was verbose. The messages themselves are not important. I'm talking about ergonomics of the api.
@lizzyfleckenstein9837
@lizzyfleckenstein9837 Жыл бұрын
@@Codeaholic1 oh ok my bad
@doomguy6296
@doomguy6296 2 жыл бұрын
While it is a nice API, it feels like a lot of effort for little reward. Consuming all this time using an API one has to learn, to eventually produce messages you could print directly. There has to be something made simple with little to remember and faster to write. We programmers understand stack errors. Why can't we just have a stack without fancy terms and methods/functions?
@mdxggxek1909
@mdxggxek1909 Жыл бұрын
You can make your own macro?
@wumwum42
@wumwum42 Жыл бұрын
I would be interested in a comparison between error stack and miette. I kinda prefer the miette naming scheme and output. In general, "crate battle" would be a cool video format. Other ideas for this format: egui vs iced vs yew, bevy vs microquad,
@ErikBongers
@ErikBongers 2 жыл бұрын
Not bad but all this inline error handling (actually, data checking in this case) makes the actual program logic rather unreadable. I still prefer the C-style "if check1_fails return; ...if check_n_fails return; ...do_the_work;" I know Rust enforces error checking, which is good, but it would be nice if all that checking could be moved up in the code.
@raffimolero64
@raffimolero64 2 жыл бұрын
Actually, every single "if check_fails { return }" is still there, condensed into a single "?" operator at the end of every function call. It's just that before we get to that point, we attach a lot more information to the error message. You can still do that style as shown at 13:18. However, there are some cases where you cannot simply return immediately as you error. Rust encourages generous use of iterators, which are functional in nature. This usually means there is work done within "closures"; anonymous functions. You have to handle errors within those closures, and only rely on the upper levels to add more context.
@zafarabdullah-xp6et
@zafarabdullah-xp6et Жыл бұрын
evry time i watch your vids like this, i get more hyped to learn rust!
@ivandenysenko
@ivandenysenko 2 жыл бұрын
Thanks for your effort, Bogdan!
@AndyQuinteroM
@AndyQuinteroM Жыл бұрын
this is an awesome video! I usually build huge enums but this approach looks awesome! perhaps it would be confusing to new developers reading the code and seeing this approach for the first time. but overall looks great
@TheZdannar
@TheZdannar 2 жыл бұрын
Fantastic crate and video. Thank you sir.
@HyperFocusMarshmallow
@HyperFocusMarshmallow 2 жыл бұрын
Looks useful. Thanks for sharing!
@Galakyllz
@Galakyllz Жыл бұрын
This video was great! Thanks for making it.
@zahawolfe
@zahawolfe 2 жыл бұрын
Really nice, error handling in rust has been so tedious so far
@muratartan
@muratartan Жыл бұрын
Thanks for your efforts,Bogdan
@kwinzman
@kwinzman 9 ай бұрын
It would be very educational to implement the same functionality with eyre, so the viewers can see the comparison of the two libraries.
@0xccd
@0xccd Жыл бұрын
Damn! That error handling is so cool. Can't wait to have it in stable
@ARS-fi5dp
@ARS-fi5dp 2 жыл бұрын
Thank you man ❤
@mikutut
@mikutut Жыл бұрын
Another great video as always! Do you, by any chance, have any plans on making a video about Tauri framework?
@famshare-esl2453
@famshare-esl2453 5 ай бұрын
Ooooohhhhhhhhh. @ 12:00 Now I see what they're going for. Thanks. I'd been curious about this library, but didn't quite grok what they were offering from a few skims. I'd be curious to hear how you think this compares to Miette -- which was around before, gathering error information into a Report type and sending forth. But with, it seems, more focus on user usable errors.
@sovrinfo
@sovrinfo 2 жыл бұрын
Thanks you a lot!! Very nice video!
@Roastercode
@Roastercode Жыл бұрын
Thanks for the video and the effort of improvement made along different videos. I see you are now working on a mac and another editor. Which one is it?
@fabiopetrillo
@fabiopetrillo Жыл бұрын
Amazing! Congrats.
@user-gs6of5vv6r
@user-gs6of5vv6r 2 жыл бұрын
@Let's get rusty, please, make video about Cow smart pointer
@gary3658
@gary3658 2 жыл бұрын
There is a good explanation of Cow at: kzfaq.info/get/bejne/brVggddq1r_DpqM.html
@finnmonstar
@finnmonstar 2 жыл бұрын
What font and what color scheme do you use? It looks different from what we have on Windows and Linux, but maybe it's because you're running VSCode on macOS.
@Speykious
@Speykious 2 жыл бұрын
Font: JetBrains Mono Color theme: Dark+ (available by default) Parentheses are colored in yellow/blue/purple too, thanks to the Bracket Pair Colorizer... which I just learned today has become a VSCode built-in. 7_7
@matiasfedericolareo7791
@matiasfedericolareo7791 2 жыл бұрын
Nice video! i found this crate a little difficult, i think error handling should be as simple as posible and should not take to much time :/
@GlobalYoung7
@GlobalYoung7 2 жыл бұрын
thank you 😊
@thurston04
@thurston04 2 жыл бұрын
I'm struggling to understand the usefulness of the crate if we already have access to expect() and match error handling. Perhaps I'm missing something?
@MrSpoomples
@MrSpoomples 2 жыл бұрын
Perhaps it has to do with style of programming and problem-space. For the things I'm currently working on, it is useful to see the errors in context to each other. Expect is incredibly useful, but sometimes you want more information around it. I also would not introduce this crate in my project until it reached a point of complexity that leaves me wishing I had better ways to handle my errors, but this is just me. I can easily see the vast majority of projects doing just fine with only what std comes with by default.
@DrIngo1980
@DrIngo1980 2 жыл бұрын
So "expect()" just panics (calls the panic!() macro) with a custom error message. Very often, especially if you write library code that is consumed by others, or even when you write a simple webservice and you don't want to end up with a "500 internal server error" on the client/browser you will need to be able to customize your error handling and decide when and how to return a proper error, or - and this is the worst-case scenario - when you actually have to call panic!(). Calling panic!() is a "using a last resort"-kinda situation and should only be used very sparingly in my opinion. Ask yourself this: if you write a database server/service and a user sends an invalid query, do you panic!() and force a shutdown of the whole database or do you return a nicely formatted error message to the user telling them their query has an issue (and ideally what issue and where (and how to fix it, if possible))? Same thinking goes for any kind of web-service/web-app. Those examples I described above are usually multi-threaded, because they serve not just one single client at a time, but can serve multiple clients at the same time. Do you really want to have the whole service exit/go down just because one client is misbehaving? No, of course not. Never actually. Also, of course I am over-simplifying things here, even calls to "panic!()" in Rust can be "intercepted", kinda - it is a quite advanced feature to use for sure, so totally not beginner friendly and hence not widely advertised. Also it is certainly not as easy in Rust as it is in other programming languages who provide a more traditional exception-based error handling, that's for sure. So, in conclusion from my point of view: your argument is completely understandable from a beginners (or even intermediate) Rust programmer's point of view, so I am glad you asked. From what I understand so far (and I've only used Rust for the last 2~3 years), it is like I explained above (someone more experienced in Rust please correct me when I am wrong (not if, because I am most likely wrong with some detail or another). That being said: error handling in Rust is still one of, if not, _the_ language features I struggle with the most. The borrow checker is "easy mode" compared to this (for myself that is, _at this point in time_ 😊).
@vanish3408
@vanish3408 2 жыл бұрын
very nice video, error handling is always pain in the ass for me
@skytech2501
@skytech2501 Жыл бұрын
This is one of the important videos. Error handling is super important IMO, I prefer the clean and deep context of error log. Moreover it provides documentation as well! Thanks 😊
@Speykious
@Speykious 2 жыл бұрын
Damn, this crate is awesome
@leighwanstead3254
@leighwanstead3254 2 жыл бұрын
May I ask which is better use enum or struct? I found that use enum just need one line code to represent one error. Struct is too many lines of code
@soberhippie
@soberhippie 9 ай бұрын
I kind of like it, because it creates printable messages in one "logical" line, that may or may not be printed/logged/displayed later, but at the same time this creates a problem if we want to localise the application later, because we haven't separated data from presentation. Can this approach be combined with "thiserror" to derive the Display and Error traits for our types instead of providing them manually?
@thekwoka4707
@thekwoka4707 11 ай бұрын
This is dope
@christerpherhunter930
@christerpherhunter930 Жыл бұрын
Thank you for showing your face as you speak. When the topic gets complicated it helps me understand what you're saying when I can see your face and mouth move as you speak. Also, thank you for not speaking while you put code into the IDE. It is helpful to be able to focus on what is being written.
@icelk
@icelk 2 жыл бұрын
Using only std, you can use Result::map_err to change the error type. You should also make all format! macros lazy. Else, the string will be created every time the function is called.
@szymek1567
@szymek1567 2 жыл бұрын
How to do format! lazy?
@Codeaholic1
@Codeaholic1 2 жыл бұрын
@@szymek1567 the lazy_format crate can do that.
@31redorange08
@31redorange08 Жыл бұрын
He did it once at 10:17 (attach_printable_lazy).
@mashfiqurbd
@mashfiqurbd 2 жыл бұрын
*good video :)*
@samansamani4477
@samansamani4477 Жыл бұрын
Awesome, but what would be easiest way to remove all lol logging from release build..? I mean it's perfect for debugging but what if we want to release the code?
@finnmonstar
@finnmonstar Жыл бұрын
i think you can do something like this #[cfg(debug_assertions)] fn init_logging() { env_logger::init(); }
@StaVykoV
@StaVykoV 2 жыл бұрын
what is that extension that shows the potential errors in red on the same line? e.i. s.parse() and then there is type mismatch.... error showing
@joshuahewlett44
@joshuahewlett44 2 жыл бұрын
“Error Lens” extension in VSCode
@StaVykoV
@StaVykoV 2 жыл бұрын
@@joshuahewlett44 Great, thanks!
@netify6582
@netify6582 Жыл бұрын
Cool but cannot shake off the feeling this is somewhat overengineered. Would like to see some more lightweight approach. Anyhow and thiserror looks quite fine to me even though it's not as robust as this approach. Last detailed root cause for the error was excellent, though!
@CheshireSwift
@CheshireSwift Жыл бұрын
Anyhow/Eyre are the lighter weight options, if you aren't interested in the detailed context info.
@SrikanthAnantharam
@SrikanthAnantharam 2 жыл бұрын
Wow
@lexk5638
@lexk5638 2 жыл бұрын
Getting some bad C++ vibes here. Too overengineered.
@jabuci
@jabuci Жыл бұрын
What is an error context?
@ZetwayBROX
@ZetwayBROX Жыл бұрын
How are you typing so fast?
@markusdd5
@markusdd5 Жыл бұрын
Excellent tutorial! I just disagree on the user-facing 'Try again' message. There is nothing to try again, the program will consistently fail. I would even argue this is the most frustrating type of error message you can give to anyone, unless trying again actually has merit. In this case, a message like 'Entry for {name} was found, but is malformed and cannot be returned.' would be much more explicit and suitable. This is a message you can then pass back to the dev, or google for and get some proper fix for it.
@user-hn1cy5ee5l
@user-hn1cy5ee5l Жыл бұрын
I would like to learn rust, but reading the code with a lot of &&, ?, ::,! - I know this is a specific of the language and this is a basics everyone should know. But if you look at the python code even though you haven't met it before, you will understand what it does. In here I see a lot of code for error handling (switching context, attaching printable, etc.) In most cases all of this code should be a template, can we achieve the same result with less amount of code?
@ddystopia8091
@ddystopia8091 Жыл бұрын
It would be so grate to use ai to generate error handling and testing for code...
@doxologist
@doxologist 2 жыл бұрын
Cool, but lost me at the Nightly requirement. Surely this can also be achieved using anyhow::Context??
@vicenzogiuseppe6500
@vicenzogiuseppe6500 Жыл бұрын
bogdan tu e foda
@KresnaPermana
@KresnaPermana 2 жыл бұрын
As always, great video But dude please get a sleep
@redcrafterlppa303
@redcrafterlppa303 Жыл бұрын
Where is the problem in returning an Box everywhere multiple Errors are thrown in one function? Also this version is very verbose in my opinion. I will use the normal error trait instead.
@lightprogrammer
@lightprogrammer Жыл бұрын
Error handling in rust is a nightmare
@jobosan4855
@jobosan4855 2 жыл бұрын
Gross I'd rather stay with Err.
@gary3658
@gary3658 2 жыл бұрын
I don't like the "error-stack" crate approach at all. It mixes bunches of successful path execution statements with bunches of failure path execution statements (e.g., parse() with report() or collect() with change_context()) as opposed to factoring out error creation and transformation into separate blocks (From trait usage). This intermingled approach is used in reactive programming libraries such as OpenCombine and it gets so tricky that it can confuse the livin' sh*t out of everyone except for absolute experts. Rust's golden rules are simplicity, readability and predictability - and that probably ain't it.
@ybergik
@ybergik Жыл бұрын
It's an incredible oversight (stupid decision) to not have exceptions in Rust and then having to develop stuff like this to emulate it in a _very_ cumbersome way.
@affegpus4195
@affegpus4195 Жыл бұрын
Exceptions implies things happening without you knowing. Thats just not what rust is made for.
@nxtktube
@nxtktube Жыл бұрын
Exceptions is a bad concept. Errors and mistakes are parts of life and expected to happen, there is nothing exceptional in them. You shoud treat errors just like another valid code branch in your program.
@muhammadharris4470
@muhammadharris4470 Жыл бұрын
too verbose. a lot of effort and reliance on an external dependency all over the app.
@daniivanov4554
@daniivanov4554 Жыл бұрын
I don't care how fast it is rust is crap
@nxtktube
@nxtktube Жыл бұрын
Rust is the best programming language ever created, after Lisp and Haskell
@linkernick5379
@linkernick5379 2 жыл бұрын
Don't cut the corners with the simple yet incomplete solutions. For the libraries I recommend `thiserror` lib, and for the applications - `anyhow`, both are maintained by David Tolnay and extended by community. Also they are tested in production, so for me the choice for the error handling library is just no-brainer. 😉
Error Handling in Rust
16:20
Let's Get Rusty
Рет қаралды 81 М.
Rust Error Handling - Best Practices
21:33
Jeremy Chone
Рет қаралды 14 М.
3 wheeler new bike fitting
00:19
Ruhul Shorts
Рет қаралды 50 МЛН
Alat Seru Penolong untuk Mimpi Indah Bayi!
00:31
Let's GLOW! Indonesian
Рет қаралды 8 МЛН
Strings in Rust FINALLY EXPLAINED!
21:40
Let's Get Rusty
Рет қаралды 74 М.
Make your custom errors fly! | Advanced Rust Part 6
31:29
Green Tea Coding
Рет қаралды 684
Building micro-services in Rust using gRPC!
9:22
Let's Get Rusty
Рет қаралды 53 М.
All Rust features explained
21:30
Let's Get Rusty
Рет қаралды 287 М.
Async Rust Is A Bad Language | Prime Reacts
28:46
ThePrimeTime
Рет қаралды 88 М.
Rust: When C Code Isn't Enough
8:26
CodeAhead
Рет қаралды 153 М.
Why JavaScript Devs are Switching to Rust in 2024
10:35
warpdotdev
Рет қаралды 248 М.
cute mini iphone
0:34
승비니 Seungbini
Рет қаралды 5 МЛН
How To Unlock Your iphone With Your Voice
0:34
요루퐁 yorupong
Рет қаралды 27 МЛН