4 ms·
Error handling patterns in Go
- wahern 9y agoCreating an interface that records the last error so that you can lazily check for success after a series operations is such a great idea that it's precisely how C stdio works ;) Years ago I thought the C stdio interface was clumsy and needlessly verbose. It took awhile to appreciate the sanity of separating fread and fwrite from ferror, feof, and fclearerr. Now I try to mimic that design in similar interfaces, especially network I/O interfaces. I had never heard it described as monadic error handling before. One gotcha I've run into is with infinite loops (or rather, loops with indeterminate number of iterations), where for various reasons the programmer forgets to check for an error at an appropriate place, or the program never reaches the check. The program might hobble along in a broken fashion, and it can be difficult to track down the bug. Example: a task run on a periodic timer with a transient error (e.g. timeout) on its connection to a message bus. One solution I implemented (in a Lua library) was to set an arbitrary limit (100, but modifiable) on the number of times a cached error is returned before throwing an exception. Thus, a caller is expected to either call the equivalent of fclearerr or to destroy the object in a timely fashion.