add some error handling + flush the buffer