The only way to prevent it is to TAPER OFF caffeine before beginning your fast. I take about three days, reducing my one weenie cup of coffee to nothing in 3 days. I have gone crazy a couple of times and not tapered off, and paid the price! Once the bad old headache starts, that's all she wrote until it's gone! All you can do is drink lots of liquids and attempt to flush it out. You should NOT take anything for it, as your liver is very vulnerable while fasting.
I started a fast at one point and hadn't tapered off. I actually drank a half cup of coffee, then a third cup, then went off and avoided the headache. Not the ideal scenario because again, the liver has to process the caffeine, but it got me through.