Change context manager to be class based with better exception handling