Improve error handling and typescript style