Handle errors from write()

Fixes #964