Error handling in the fmt package?

How to know if fmt.wprintf failed? It doesn’t return an io.Error. It seems to return the number of bytes that would have been written although it’s not quite documented behaviour.

I also can’t see how to use fmt.bprintf. It returns a string so I can get the length of that. But if the string length is exactly equal the buffer length I don’t know if it was exactly the right size or if it wanted to write more.

I can’t find a way to tell if an io.Stream is in a failed state. One workaround is to implement my own io.Stream to catch the error at check it after writing a whole file.

I would totally create an io.STream with my own writer proc that can track the first error that fmt.wprinf throws away, then pass it to it.

I don’t think there’s anything built-in.

You can do the same with your own wrapped proc that does the same as fmt.bprintf (source link) as well - create a string builder and call wprintf with your wrapped io.Stream proc.

The documentation talks about it returning the bytes written, not what it would write. Do you have any examples where it returns a different value?

Yeah, I guess there is a workaround. It seems like a bit of an omission in the fmt package to not forward the io.Error but I don’t know if there was a rationale behind it.

The implementation of io.wprintf ignores the error and keeps writing to the stream. So the stream did write them in some sense even if the underlying file is in an error state.

Even if the io.wprint would check for errors there’s no guarantee that the absence of error means anything got written to the file because the stream can be buffered an the error not detected until it tries to flush the data.

So I can sort of see how returning an error value isn’t actually that useful except that you can likely stop writing a large file a little earlier, which could be nice.

I never wanted to know the number of bytes written except in C where snprintf allows me to allocate a buffer of the correct size.

So the behaviour is kind of reversed from that of C and I would need workarounds to do the expected thing in both use cases.

2 Likes