Mine did this a lot years ago - bad PCM relay in the box next to the battery. Turns the ignition module and fuel system on/off. Usually you will get a 543 code which is secondary system shut down. Does this because the primary system failed so it kills it; safety circuit in case you are in a wreck. Brown relay, same as the horn relay so you can swap them. Mine would open up, sometimes the engine died, other times it would hesitate.
Problem would come and go, it was hard to catch until it died in my driveway close to my meter and wiring diagrams. Ford garage replaced the fuel pump, a wiring harness, spent hours in the shop under warranty and they couldn't fix it. They forgot to go to the basics. I found 4 volts on a 12 volt circuit.