A police officer’s dashcam captured the moment the officer’s cruiser was nearly hit by an oncoming train.

It happened at a crossing in Mokena, Illinois.

Officer Peter Staglewicz nearly drove through a crossing when a train came speeding down the tracks last month, but swerved at the last minute, WLS reported.

>> Read more trending news

It turns out there was an electrical problem with the crossing gate. It wasn't the first time someone was almost hit by a train at that crossing. Other drivers told WLS there have been other near-misses there.

At the time of Staglewicz's near accident, the warning lights were flashing but only when the train was already near the crossing. The gates failed to come down until the train was crossing the road, WLS reported. A car in front of Staglewicz was able to clear the tracks before the train barreled through.

Officials with Metra, the commuter railroad in the Chicago area, said there was a short in the crossing gate and it was repaired a few hours after Staglewicz was nearly hit, WLS reported.