Added error handling to foreign functions