A "sacrifice" itself doesn't mean anything - the chess board is what matters.
So if you do anything on the board that doesn't work (your opponent has a way to respond that beats you), then you will end up losing/getting a worse positions/losing your advantage.
What you just asked is essentially "how to get better at tactics", and tactics is the art of choosing between different moves (including to sacrifice or not) and tactics is an extremely difficult topic!
However, in the above case, it's not that hard. All you have to do is ask yourself - what would my opponent do if I did this?
i consider myself a tactical player not positional, therefore when i get better i'd like to do sacrifices for a king attack or promoting a pawn etc. now i have done some scarifies in the past but either usually my opponent can counter it.
the idea behind a sacrifice usually works it's just that i miss something that actually makes the sacrifice pointless for example.