improve on_close and on_error handling

also add tests
improve on_error handling