Handle errors from write()

Fixes #964
Replaces #965