How to capture error details within a while loop? … in PowerShell

I have a power shell script that checks if the connection to an Ip address is live. I have added a timer to the code so it loops and checks for 4 minutes then sleeps then starts again. I have also added this script to task schedule that runs every 5 minutes.

However my problem is the script only capture the error details if the errors occurs outside the while loop. If there is an error while the code is looping, the error variable is empty and unfortunately all the errors occur withing the loop.

This is the code I have. Apart from the above, everything works fine. Any suggestions or answers?

function Make_Decision() {
    if ($val -eq 0) {
        $msg = "Connection to [$IPaddress] FAILED`n"
        Add-Content -path C:\path\results.txt -value "[$date] - { $msg }"

## Connection Test Function
function Test_Port_Connection() {
    $date = Get-Date -Format g
    $portNumber = 0000
    $IPaddress = ''
    $timeout = new-timespan -Minutes 4
    $sw = [diagnostics.stopwatch]::StartNew()
    ## Establishing TCP Connection
    $host_connection = New-Object System.Net.Sockets.TCPClient
    try {
        $host_connection.Connect($IPaddress, $portNumber)
    catch {
        $erro = "[$date] - $_"
        #Add-Content -path C:\path\errors.txt -value "[$date] - { $erro }"
        $erro | Out-File C:\path\errors.txt -Append

    while ($sw.elapsed -lt $timeout) {
        #while loop starts
        if (($host_connection.Connected) -and (Test-Connection -IPAddress $IPaddress -Count 1 -ErrorAction SilentlyContinue)) {
            $val = 1
        else {
            $val = 0
        start-sleep -Seconds 1
    } # end of while loop