My STM32 is bricked (can't run anything in STM32CubeIDE) because my main loop has no sleep, after i add it back, my STM32 can run many times in STM32CubeIDE. To recover my weact blackpill, i use "while true; do st-flash erase; sleep 0.25; done" to keep running the st-flash command, I found out pressing the BOOT and RST buttons on the board NO HELP. Just run that command and keep plugin and unplug the jtag to usb port, then it works. Also remember to plug in the usb to the board too, it needs 5v to erase flash, JTag only provides 3.3v not enough.

When my weact blackpill is bricked, it goes crazy for the st-flash command, the flash size are different in different runs of st-flash

After the stm32 successfully come back, you can see the st-info command can dump out correct data

Better approach 1
add HAL_Delay(200); in "USER CODE BEGIN Init" and use "st-flash --connect-under-reset erase" instead of "st-flash erase". Then press the reset button on the board and enter "st-flash --connect-under-reset erase" immediately