One thing to remember: (re)lapsing doesn't erase the experience you've racked up while moderating/abstaining...it's very common for folks to feel that a lapse has ruined their clean time. But while it's true that a lapse is usually a bummer (and of course can be dangerous), it doesn't detract from your prior accomplishments.
With that said, building skills to reduce the kinds of slips you've described is an important part of long-term recovery. I think it's one of the hardest parts, in fact...those moments can sneak up with so little warning.
Personally, here's what I try to do. If I suddenly get an impulse to use--and if I'm aware enough and composed enough to resist it--I try to change my 'setting' (i.e. where I am and what I'm doing) ASAP. Sometimes simply going into another room and cranking up some music works. But more often I get urges to use when I'm rattling around the house alone, feeling bored/depressed, and in such cases it's important for me to get less isolated quickly. I'll do almost anything...I go to the movies--any movie...I go to the hardware store...I go sit in a cafe and read a trashy magazine...pretty much anything to get outside my head. If you have someone you can talk to with sufficient honesty, that can be great too.
For me, it's all about experimentation, learning what works and what doesn't and keeping some workable strategies right in the front of my brain.