Why is my TRY ... CATCH not working?

My CATCH is not catching the error, what am I doing wrong please? HTML
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Github Profiles</title>
</head>

<body>
<script src="script.js"></script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Github Profiles</title>
</head>

<body>
<script src="script.js"></script>
</body>

</html>
JAVASCRIPT
async function getUser() {
try {
const res = await fetch('https://api.github.com/users/uiouiouiouiouio');
const data = await res.json()
console.log(data)
} catch (err) {
console.log('Error: ' + err)
}
}

getUser()
async function getUser() {
try {
const res = await fetch('https://api.github.com/users/uiouiouiouiouio');
const data = await res.json()
console.log(data)
} catch (err) {
console.log('Error: ' + err)
}
}

getUser()
9 Replies
Jochem
Jochem•14mo ago
what is the output?
Blackwolf
Blackwolf•14mo ago
I am getting a 404 error
Blackwolf
Blackwolf•14mo ago
No description
Blackwolf
Blackwolf•14mo ago
surely my CATCH should handle this being an error, shouldn't it ignore the "console.log(data)" ?
Jochem
Jochem•14mo ago
404 is a valid result for fetch, it isn't an exception you requested a resource from the server, and the server responded that it couldn't find the resource an exception would be if you can't reach the server, or DNS resolution fails, or the connection is reset mid-transfer
Blackwolf
Blackwolf•14mo ago
how do i catch the 404 error i want to be able to report "user not found"
Jochem
Jochem•14mo ago
you'll have to examine res, it will contain the HTTP status code of the response
Blackwolf
Blackwolf•14mo ago
ahhhhh, gotcha, thank you this worked

async function getUser() {
const res = await fetch('https://api.github.com/users/uiouiouiouiouio');
const data = await res.json()
console.log(res)
if (res.status == "404") { console.log('Error: ' + res.status) } else {
console.log(data)

}
}

getUser()

async function getUser() {
const res = await fetch('https://api.github.com/users/uiouiouiouiouio');
const data = await res.json()
console.log(res)
if (res.status == "404") { console.log('Error: ' + res.status) } else {
console.log(data)

}
}

getUser()
thank you 🙂
Jochem
Jochem•14mo ago
no problem 🙂 Glad to help!
Want results from more Discord servers?
Add your server