Refactor error management