The answer is twofold - learn your opening theory, and learn how to defend.
If you can defend yourself against the attack, then you're not "castling into the attack", you're simply castling. Of course, you could be wrong, and castling could be a mistake, but that's chess - you have to make tradeoffs, trust your instincts, and calculate the position.
In most openings, opening theory tells us whether the risk/reward tradeoff of castling on a given side of the board is worth it. You never see white castling queenside in the Grunfeld, and that's becaues we know from opening theory that it's too risky. An advanced study of the French and Sicilian defenses helps a player gain a better intuition for when it is and is not okay to castle kingside.
Sometimes, of course, we don't even know, and castling is a gamble. In the Sicilian and Caro-Kann defenses, black often castles kingside without being sure whether or not it's a suicide move, and hopes that his counterplay and defensive abilities are stronger than his opponent's attacking abilities.
There really is no way to say "in positions with these features, you can castle, and in positions with these features, you can't" unless you're a computer playing computers. Learn opening theory so you can get a good intuition for when it is and is not okay to castle (If you think it might be, it probably is) and then become a better defender so you can defend yourself against whatever attacks your opponents may choose to throw at you. Unless you're playing Houdini or Kasparov, your opponent is unlikely to execute his or her attack perfectly, and it is a test of skill rather than a positional decision.
Of course, sometimes it's really obvious that you shouldn't castle, like when you have a totally fractured kingside. But categorizing such positions would be pointless because what matters is context. Similarly, if all your opponent's pieces are on the kingside, that's also a sign that you shouldn't castle there. You have to have faith in your defensive abilities, though, otherwise you'll find yourself being afraid to castle just because your opponent played