Programming is a constant roller-coaster oscillating between moments of glory and abysmal bugs.
There are days where you spend hours trying to do something and still fail. It feels terrible, because there is no way to make up for lost time.
But solving bugs is often a matter of persistence: you attack from different angles, reproduce the conflicting conditions leading to the horrendous outcome, and always strive to simplify your code. I have yet to post anything on Stack Overflow, because there is always a solution to work out.
The sour feeling is hard to deal with though. The anxiety, the powerlessness, the inability to solve the damn thing... it's perhaps the most exasperating thing about coding apps.
The only sane way to approach a bug is to step away. We lose as soon as it becomes an obsession, so the only thing to do is to take a deep breath, savor a coffee, and have a walk. Only then can we start a new repository to isolate the bug, search for a solution through trials, experiments, and plenty of Google searches, and fix it. If it takes more than an hour or two, I find it best to leave it for another day and work on something else.
Unit tests are always a good thing to have, but as Donald Knuth said, tests show the presence, not the absence of bugs. It's only one tools among many.