The simple fact with homebrewing is that sooner or later you will mess up. This is part of the reason our 1 gallon kits are so useful, because dealing with 5 gallons of bad ale is a disheartening task. But much can be learnt from the situation with the right mind set.
First, keep a Log book. Every time you do a brew record any little detail about it, even if it is not your own recipe. Measurements, what you have done differently, how long it took to brew and most importantly any factor that seems off. By doing this it makes tracking down what exactly went wrong and how to fix it much easier, but also helps you identify what changes were beneficial.
Clean everything. No really, nuke the entire site from orbit. It's the only way to be sure. Even if you have identified where the issue came from you don’t know how much has now been affected, wild yeast for example is especially hard to get out of plastics. It is also a good time to look over everything you used in case there were little cuts or cracks where bacteria could live. This means even if what you assume was the issue is wrong, you may have dealt with it anyway. You should also keep your kitchen or work area clean while brewing, even an open window may let something waft over into your brew.
Make sure all your ingredients are also clean. Anything bought from our store has been kept clean and dried, but if you are picking your own ingredients that is another matter. The boil would hopefully kill most nasty things but you may have been unlucky and found a resistant strain. The best course of action then is to place the ingredients in boiling water for two minutes, then dry them in your oven or a food dehydrator. Your ingredients should always be kept in a cool dry place preferably not in the open.
This should all help with avoiding the same mistakes again, but what do you do with your brew now?
For every brew you do no matter how bad it goes, keep a bottle or two. Most likely it is not going to turn out pleasant but a small sip or smell might help you identify what went wrong. You should also simply observe it for features like an abundance of protein. Studying the bad ale will help you identify these features earlier next time.
You can also use that one for experiments. If you are interested in not adding extra sugar for bottling or adding ingredients to the bottle after a brew, it is better to try it out on a bad ale than a good one. Because if it goes wrong you haven’t really lost out on anything, if it goes right then you have discovered a new way to brew.
The most important thing is to not be disheartened. This will happen to even master alesmiths, in fact learning to deal with failures is part of what makes you become one.