0

My program prompts the user to enter an IP address of an API, and then makes a call to that IP address. 2 of the error cases are

1: An invalid IP Address is entered. The POST call returns "net::ERR_ADDRESS_UNREACHABLE"

2: The certificate of the site at the given address is not trusted. The POST call returns "net::ERR_CERT_AUTHORITY_INVALID".

These two different scenarios should be addressed differently, but I can't find a way to tell which error is returned. Is there a way to distinguish between these returned errors with code?

Code:

function pingBridge(ip) {
    var username = 'username';
    var url = 'https://' + ip + '/api'

    const result = new Promise(function(resolve, reject) {
        fetch(url, {
            method: 'POST',
            body: JSON.stringify({'devicetype': username})
        }).then(function(data) {
            console.log('success')
            console.log(data)
            resolve(data.json())
        }).catch(function(error) {
            console.log('error')
            console.log(error)
            reject(error)
        })
    })

    return result
}
Devan
  • 1
  • 1
    What libraries are you using? Namely, where is the `fetch` function defined? – Sumner Evans Jan 03 '21 at 05:21
  • 1
    @Devan try using the error object when the issue is caught in the catch block. You can try the error.message or error.status to differentiate both. Try first with error.status first code. – Sats Jan 03 '21 at 05:31
  • @SumnerEvans - it's a part of javascript - ergo, no library needed. Here y'go: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – enhzflep Jan 03 '21 at 06:33
  • @SatishPai the error message is the same for both, "Failed to fetch". The error status is undefined. – Devan Jan 03 '21 at 07:11
  • @enhzflep, oh, didn't know that existed. Thanks for pointing it out! – Sumner Evans Jan 03 '21 at 14:26
  • @SumnerEvans - A pleasure and you're welcome. :) – enhzflep Jan 03 '21 at 14:28

0 Answers0