Improve error handling when writing