Seems to me you need to check if the currentSObject
that is set by getSobject()
is null before trying to get the child field from it.
This will occur if the relationship from the parent to child object is undefined. I.e. The Case doesn't have a Contact Id set.
Revise the loop to:
while (fieldPath.contains('.'))
{
List<String> pathPartList = fieldPath.split ('[.]', 2);
currentSObject = (SObject) currentSObject.getSobject(pathPartList[0]);
if (currentSObject == null) { return null; }
fieldPath = pathPartList[1];
}