Added error handling for message index