How can I catch a 404?
Use the HttpStatusCode Enumeration
, specifically HttpStatusCode.NotFound
Something like:
HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
//
}
Wherewe
is a WebException
.
How to handle 404 error in a async/await?
Fetch API doesn't throw errors on any status code. It only throws errors on network failures, i.e. when it couldn't finish the request itself.
You can use response.ok
to check if the request finished with 2XX
status code.
async getCoord() {
const postcodeAPI = `http://api.postcodes.io/postcodes/dt12pb`;
let response;
try {
response = await fetch(postcodeAPI);
if (!response.ok) throw new Error('Request failed.');
}
catch (e) {
console.log(e);
};
};
You can also explicitly check the status code if you need:
if (response.status === 404) {
// handle 404
}
As for your question about logging 404
errors in the console, there's no way or need to avoid it. Whenever you make a request, it's being logged in the dev tools. But dev tools are just what they are called - tools for devs. You can safely assume your users won't look there and even if someone does, having 404
there is not the end of the world.
JavaScript - How to handle 404 error in fetch?
you can check for response status to handle 404 or other errors
use below example:
fetch('your url goes here')
.then(response => {
if (response.ok) {
return response.json()
} else if(response.status === 404) {
return Promise.reject('error 404')
} else {
return Promise.reject('some other error: ' + response.status)
}
})
.then(data => console.log('data is', data))
.catch(error => console.log('error is', error));
http.get - how to properly catch a 404
Your problem is on the line
const body = error.json() || '';
The problem is that when your back-end sends an error (here being a 404), you don't send a JSON object. So if you use error.json()
, don't expect to get a JSON object !
Either you return a JSON error from your back-end, or you don't use the json()
function in your error handler.
When you don't use the json()
function, you also gain access to the status
property (if I recall correctly it's this one) which contains the error code. So you can put conditions on it, like if it's 404, you do what you want.
I hop I made myslef clear, if not, feel free to ask for more details !
Catch a 404 error for XHR
A 404 status will not trigger xhr.onerror() because, technically it's not an error; the 404 itself is a valid response.
One solution is to use the loadend() handler, which fires no matter what. Then check the status for 404, or whichever status you're interested in.
xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onloadend = function() {
if(xhr.status == 404)
throw new Error(url + ' replied 404');
}
The same method exists for XMLHttpRequestUpload.
Unfortunately, our browser vendors don't allow us to programmatically suppress network errors in 2017. However, networks errors can be suppressed using the console's filtering options.
Related Topics
How to Embed an Application Manifest into an Application Using VS2008
Casting List<T> - Covariance/Contravariance Problem
Why Is Typedreference Behind the Scenes? It's So Fast and Safe... Almost Magical!
Write to Windows Application Event Log Without Event Source Registration
How to Install a Certificate into the Local MAChine Store Programmatically Using C#
What Does the Keyword "New" Do to a Struct in C#
Get the Property, as a String, from an Expression<Func<Tmodel,Tproperty>>
How to Change the Font Color of a Disabled Textbox
How to Remove Accents on a String
How to Delete a Registry Value in C#
How to Read Regex Captures in C#
For I = 0, Why Is (I += I++) Equal to 0
Is Enabling Double Escaping Dangerous
What's the Difference Between Anonymous Methods (C# 2.0) and Lambda Expressions (C# 3.0)
How to Insert a Data Table into SQL Server Database Table
ASP.NET MVC Dropdownlistfor with Model of Type List<String>
How to Get the Kestrel Web Server to Listen to Non-Localhost Requests