It sounds like some kind of anxiety disorder or what can be called "racing thoughts." There are generally patterns to this type of thinking. If you are able to identify the patterns it is possible to stop the thoughts before they become out of control. A Cognitive Behavioral Therapist can help with this. They can also help you to determine if the thoughts have basis in truth or if they may be assumptions. We often make assumptions when racing thoughts occur. One assumption leads to another to another and it becomes out of control. One example might be
"I always fail."
Statements of always or never are very rarely true. One might replace that thought with something like:
"I have succeeded at. . ."
A therapist can help you do identify those thoughts and try to replace them.