Improve consistency of error handling

Ensure that all errors are handled in a consistent way and cap the buffer size
to prevent any chance of run-away buffers.