fix database leak
improve error handling