Refactor error handling and fix dialyzer errors