Exclude Outside Edges of overlapping Outlining

Hi,

here i have a simple outlining example:

As you can see there are edges that are drawn above the wall that is in front of that character.
Is there a generic solution to create an excluding mask. My problem is that occluded parts are also the rest of the scene, so i cannot differentiate between that wall and the rest of the scene.

Thanks in advance for any giving tips and tricks.

Cheers