When is unwrap() ok?

An example of where I am using unwrap is serialising a query.

I think that is perfectly ok ( at least for my situation ). I also use unwrap when using channels, as any errors are internal programming errors, not "user errors". However, I probably shouldn't be using it for bad program parameters, although the consequences there are fairly minor (a rapid panic on server startup, just not the greatest error message ).

The name sm.st.x.qy is kinda inpenetrable so it's hard to be sure, but I would say this is perfectly fine as long as you are in full control of that field's contents and it makes sense to assume serialization will never fail.

Realistically, if the format you are serializing to can handle all the types that sm.st.x.qy throws at it, then this should be a sound assumption. It's not like writing to some W: Write where failed writes are expected to occur.

Also, as much as we would like to tell ourselves otherwise, it's not a massive deal if your code is sloppy or ignores edge cases. 9 times out of 10, if your program crashes due to a bug/oversight then it'll be automatically restarted and the user will just try again.

Yeah, that's my thinking as well.

I mean, it's annoying, and if you are deploying this to the cloud it could crash+restart over and over, but a lot of those systems are designed to handle this situation by automatically rolling back to a known good version if you don't get happy health checks after starting so it's not a critical issue.

2 Likes

qy is just a bunch of strings:

So it isn't going to fail, unless something in serde is crazily broken or something.

1 Like

If the only one who could fix the problem is an engineer -- such as by making a new build -- then unwrap is great. Getting a stack trace right on startup is definitely one of the easiest things to deal with, and getting a pretty "serialization failed" message from ? propagation is often substantially worse.

For example, I'm much happier with my webserver aborting at startup for bad routing tables than some of the routes "gracefully" not working at runtime.

1 Like

I would use .expect instead and have a more meaningful message.

3 Likes