If you know when you're most likely to write buggy code, you're already a bit ahead of the game! ;)
1) what to do on those days
Do you have non-coding tasks you could be doing? Update your priority list or schedule, review meeting notes, catch up on documentation, answer emails, etc. I usually go with those things when I'm unmotivated, and it leaves me happier and more productive the next day because I don't have those boring tasks hanging over me.
If that's not an option, try to find a coding job that's reasonably simple and self-contained, if you have any of those.
If your work hours are flexible and you're really having trouble being productive, you could go home early - no point in training yourself into staying at work when you know you're not getting much useful stuff done.
2) how to avoid them
This is a much trickier question. Do you have any idea what causes them? Is there any pattern you noticed? Lack of sleep or exercise, too much partying the day before, personal issues distracting you from work, a feeling that you're not sure what you should be working on, simply burnout from a too-heavy workweek? The solution will obviously depend on all those.
Some things I would try, if you're not sure what the problem is:
- review your priorities to make sure you have a clear idea of what you should be doing - personally when I'm feeling unmotivated it's often because I'm feeling too overwhelmed by my task list.
- go for a long walk, or better yet go to the gym if you can. The added energy may help.
- go for lunch or coffee with a coworker you like - interesting conversation may be enough to snap you out of the mood.
- try a "30 minutes of work, 15 minutes of fun" schedule for a while (adjust the numbers to whatever works for you) - maybe you'll do better at concentrating on work if you know you're only doing it for a short time, and 30 minutes of focused work are probably better than an hour of unmotivated staring at the screen.