better error and close event handling