I work for a banking firm and we have built so many custom tools and wrappers around literally everything that sometimes I forget how these APIs work in their base form. Appreciate you James.
@JamesQQuick Жыл бұрын
You're very welcome!
@Ghandmann1 Жыл бұрын
Minor correction: Fetch only throws on network error (can't connect, connection interrupted, DNS failed, etc.) but not on status code 500. Every valid http request-response cycle is just that: valid for fetch. The interpretation of the status code is left to the developer.
@JamesQQuick Жыл бұрын
Ahhh great point! Thanks for clarifying that!!
@fennecbesixdouze1794 Жыл бұрын
This isn't a minor correction.
@billygnosis Жыл бұрын
The `Response` interface has a property that allows you to check whether or not the response was successful (200-299). So you can just write: `if (!response.ok) { ... }`
@chadbekmezian4806 Жыл бұрын
This is what I always do
@bigbadcatbigbcy293310 ай бұрын
oh thanks
@MentorAliu Жыл бұрын
i like to throw error with status code if(!response.ok) and then in the next if statement check if the response is json, because sometimes you receive templates and you want to handle that as well, if everything else goes right i return the json
@JamesQQuick Жыл бұрын
That's a great option! Thanks for sharing that!
@JamesLaenNeal Жыл бұрын
Yeah, I think this is the "correct" way to do it. Though less common, there are other HTTP statuses that may accompany a still-successful request.
@wilofgren Жыл бұрын
I try to route all my requests through a single service and run my response through a handle error function that returns an alert with the error status code and status text.
@MentorAliu Жыл бұрын
@@JamesLaenNeal yep, best approach is to discuss with the backend about specifics, usually each team requires different ways to handle the status codes, it's not jack of all trades, also libraries require specifically to throw errors so they can catch it in the view and manipulate the view according to the error, (example show a popup if a post request failed), TanstackQuery one of the libraries
@kovoliver9 ай бұрын
I think the proper approach is, when you develop a JSON REST API, you must send the body always in JSON format, including when the status is 4xx or 5xx. So the basic error is in the API implementation, but of course, you have to deal with this in the case of some APIs.
@ebrahimmehri5 ай бұрын
Excellent! I'm a professional KZbin uploader myself and I'm quite aware how difficult it is to make a single video. Bravo! Keep up the good work.
@davorinrusevljan6440 Жыл бұрын
I did that mistake quite a few times. There is res.ok property that can be checked. If not true I usually throw an error
@JamesQQuick Жыл бұрын
Ah that's a nice one as well!
@juanmacias5922 Жыл бұрын
That makes sense, we should be checking the status code!
@emilemil13 ай бұрын
I would go a step further and also validate the body before parsing it. Sometimes you get a 2xx response but the body is not at all what you expected, sometimes it may even contain an error. I've also used services that sometimes returned redirect status codes (30x) on both success and error so the code was basically useless.
@neontuts5637 Жыл бұрын
Thanks for sharing James. I thought the catch() method catches all types of errors.
@JamesQQuick Жыл бұрын
I always assume the same thing lol Fetch doesn't consider other statuses except 5xx to be errors
@swildermuth Жыл бұрын
Great video!
@yayuyo7188 Жыл бұрын
In this video, the console.log output is displayed right next to the source code. Is this a vscode extension? It looks very useful!
@ongke3655 Жыл бұрын
it's quokka
@JamesQQuick Жыл бұрын
Yeah its the quokka extension. It's so good!!
@yayuyo7188 Жыл бұрын
Thx bro!
@ThanHtutZaw3 Жыл бұрын
Quick Question: How can I show fcm notification in foreground instead of toast or new Notification() without action button support.
@Stoney_Eagle Жыл бұрын
I'll keep using axios 😂 still gets the job done very well.
@JamesQQuick Жыл бұрын
haha whatever works
@lucneville7925 Жыл бұрын
Us too using an interceptor to handle error status codes, makes for a lot cleaner code
@Okir09 Жыл бұрын
Hi James, noob question but how do you get directly your console.log in the IDE next to it? : O thanks
@JamesQQuick Жыл бұрын
It's the Quokka extension. really cool. Highly recommend it :)
@Okir09 Жыл бұрын
@@JamesQQuick thank you!
@JamesQQuick Жыл бұрын
You're very welcome! That's what i'm here for!@@Okir09
@AlThePal78 Жыл бұрын
Great video
@jordan4220 Жыл бұрын
Probably should also check if the content type is application/JSON.. we once had an nginx proxied rest API throw from nginx because the upload payload was too large and it returned an html error page which the UI code gladly tried to parse as JSON 😅
@JamesQQuick Жыл бұрын
Ah yes another great callout!
@AlThePal78 Жыл бұрын
Could you make a status switch statement
@JamesQQuick Жыл бұрын
Absolutely you could!
@AlThePal789 ай бұрын
why do you have import here? Is it because it is a REACT.js fetch?
@ondrejhavazik4124 Жыл бұрын
Very helpfull video James! I also thought, that 4xx is error which should be catch :-D. Can I ask you, I assume you are using quokka and you have to use 'node-fetch' library for create API requests, this library is installed globally or somewhere in your project? Thanks! :-)
@JamesQQuick Жыл бұрын
Yep, using Quokka. With Quokka it gives me the ability to install packages for a given file. I think that's with the paid tier though. It may not be available on free tier. Try it out and let me know!
@BorisBarroso2 ай бұрын
What I do is throw an error if the status is not 200 and you can sometimes prase de json and send as error status ===422 let errors = await resp.json() throw errors
@nopainnogame98976 ай бұрын
if I check if (!response.ok) {} is it not the same?
@kabal911 Жыл бұрын
This kind of annoyed me coming from axios. But then I realized that’s fetch’s api is actually much nicer. It assumes that if it gets a server response, its job was successful. Who’s to say you aren’t calling some wacky API where 500 is an acceptable and expected status code And I don’t want libraries choosing to throw exceptions for non exceptional things If I give it an endpoint that it is unable to connect to, then I am fine with the exception being thrown for me
@JamesQQuick Жыл бұрын
Yeah axios is great also. Just depends on what you need to do with the response.
@braveitor Жыл бұрын
which extension is that that shows json response within vscode?
@JamesQQuick Жыл бұрын
It's the Quokka extension! It's awesome :)
@braveitor Жыл бұрын
@@JamesQQuick Thanks!! It seems really useful! I'm installing that right now. Good job and thanks for all your videos. Very informative and interesting.
@JamesQQuick Жыл бұрын
Yeahhh! Let me know what you think :)@@braveitor
@j4nch Жыл бұрын
I'm not sure to get the point, if in both case(40x and 50x) we get an error in either the fetch or the json. In either case, I would log an error with all the info I could have(url and status) and provide some error status after.
@jimothyus Жыл бұрын
What if the server responds with a status 400 and returns valid json telling you what you did wrong in the request? Fetch wont throw and neither will json parse. Point is you have to look at every api specifically.
@JamesQQuick Жыл бұрын
Yeah the overall point is you have to inspect the response appropriately to ensure it's doing what you expect
@alexanderkomanov4151 Жыл бұрын
Great!
@blackpurple9163 Жыл бұрын
Should the catch block catch all errors in fetch? Why hasn't that been the case yet if fetch has been here for so long already
@JamesQQuick Жыл бұрын
Catch block while catch all errors, yes. The point is that Fetch doesn't consider most things to actually be an error.
@blackpurple9163 Жыл бұрын
@@JamesQQuick ooh, so it's the fetch that's the problem here, have they not fixed it yet or is fetch fundamentally different? Because I heard in many videos that fetch will always return a response in it's promise, it won't throw direct error, is this what they were referring to?
@JamesQQuick Жыл бұрын
That's mostly true. As @ghandmann1 said below, "Fetch only throws on network error (can't connect, connection interrupted, DNS failed, etc.) but not on status code 500. Every valid http request-response cycle is just that: valid for fetch" @@blackpurple9163
@blackpurple9163 Жыл бұрын
@@JamesQQuick so your implementation will catch most of the errors right? I'm new and was taught to use axios, but fetch is how I learnt promises and async-await so fetch is what I prefer, and less libraries I ship the better I think my end product will be
@JamesQQuick Жыл бұрын
Using try/catch means all errors will get caught from any code that runs inside of the try block. You just have to manually inspect the response from the fetch request to make sure it returned the status you expect.@@blackpurple9163
@thecoderguy_0001 Жыл бұрын
whats that quokka thing in the terminal?
@JamesQQuick Жыл бұрын
It's an extension that live reloads your code. It's really awesome!
@thecoderguy_0001 Жыл бұрын
@@JamesQQuick oh will try it
@ifeanyinnaemego Жыл бұрын
Nice one
@alexanderbelkin59782 ай бұрын
Лукашенко одобряет!👍
@CodeWithHarshu Жыл бұрын
How you calling the await method without the async function
@JamesQQuick Жыл бұрын
Latest versions of node allow you to run top level await :)
@cranberry888 Жыл бұрын
@@JamesQQuickdidn't know that wow!! so many new information, james thanks a lot!
@JamesQQuick Жыл бұрын
Yeah! Happy to help :)@@cranberry888
@bigbadcatbigbcy293310 ай бұрын
good to know
@harshvardhanthakur46885 ай бұрын
hey its helps me
@BoZZstuDIOSin1981 Жыл бұрын
thx.
@JamesQQuick Жыл бұрын
You're very welcome! Have you made that mistake before?
@0x007A Жыл бұрын
Not checking the status of an API request is pure amateur or hubris of the part of the programmer. Catching the error as early as possible saves countless hours of debugging.
@VivekYadav-up7uu Жыл бұрын
Nice
@taquanminhlong Жыл бұрын
for me, i'll just make my api return json {error: "Not found"} with status 404 then it's fine to do await res.json() from js 😂
@JamesQQuick Жыл бұрын
haha yeah that works if the API is built that way. Depends on the API
@Serpsss Жыл бұрын
A tiny correction: developerasaurus isn't a valid pokemon... yet. Give it time, Nintendo have already started scraping the bottom of the barrel that's why I try to ignore anything post Hoenn 😂 (gba).
@JamesQQuick Жыл бұрын
haha one day I'd love to see developerasaurus become a real pokemon :)
@GildwareTechnologies Жыл бұрын
The JavaScript Fetch API is a modern and powerful built-in feature that allows you to make network requests (e.g., HTTP requests) from a web page or application. It provides a more flexible and promise-based alternative to the older XMLHttpRequest (XHR) API for making asynchronous requests to servers and fetching data from external resources like APIs, databases, or other websites. Here are some key features and concepts related to the JavaScript Fetch API: 1. **Promises:** The Fetch API is based on Promises, which provide a way to handle asynchronous operations more elegantly and avoid callback hell. Promises allow you to write cleaner and more maintainable code for handling responses. 2. **HTTP Methods:** Fetch supports various HTTP methods, including GET, POST, PUT, DELETE, and more. These methods determine the type of request you want to make to a server. 3. **Headers:** You can specify custom headers in your Fetch requests, which is important when working with APIs that require authentication or expect specific headers. 4. **Request and Response Objects:** The Fetch API uses Request and Response objects to represent the request being sent and the response received. You can customize request parameters and handle response data using these objects. 5. **JSON Parsing:** Fetch makes it easy to work with JSON data, which is commonly used in modern web applications. You can use the `.json()` method on a response object to parse JSON data from the response. 6. **Error Handling:** Fetch allows you to handle network errors and HTTP errors (e.g., 404 or 500) gracefully, providing better error handling capabilities compared to traditional XHR. Here's a basic example of how to use the Fetch API to make a GET request: ```javascript fetch('api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); // Parse JSON data from the response }) .then(data => { console.log(data); // Process the fetched data }) .catch(error => { console.error('Fetch error:', error); }); ``` In this example, we fetch data from the `api.example.com/data` URL, check if the response is successful (status code 200), parse the JSON data, and handle any errors that may occur during the request. The Fetch API simplifies many common tasks associated with making network requests in JavaScript, making it a preferred choice for modern web development. If you're interested in scholarships, you can explore opportunities like the one available at www.gildware.com/scholarship to support your education and career in web development, which may include working with the Fetch API for data retrieval.
@AngeloTadeucci Жыл бұрын
wtf is this chatgpt type of response lol
@JamesQQuick Жыл бұрын
bahahah feels like it!
@omega.developer Жыл бұрын
🎉
@vatmanzlokuz6805 ай бұрын
wtf,who deserialize a request without check status code xd
@liu-river Жыл бұрын
Can't trust APIs to give you the right status code, what if guy who designed API decided to return you null or undefined, then there is no error. Best to read API doc so you know what to expect. This is a stupid JS design, it's not an error first language, instead we got to work with stupid try catch.
@kevinzunigacuellar Жыл бұрын
I made this error yesterday, stole about 30 minutes of my life 😿
@JamesQQuick Жыл бұрын
hahah glad to know I'm not the only one
@MrMudbill2 ай бұрын
if (!res.ok) throw new Error()
@mario_luis_dev Жыл бұрын
don't you get around all this by using the old `promise.then()` api? I still don't get why ppl are so crazy about the async-await syntax... it doesn't seem to do anything better than `promise.then()`
@0x007A Жыл бұрын
async-await is cleaner - while both accomplish the same outcome it is easier to read and reason about than a promise potentially followed by a chain of then clauses. However, knowing how and when to use both methods is preferable. You never know when you might have to read someone's source code.
@mario_luis_dev Жыл бұрын
@@0x007A that's the thing...I keep hearing everyone repeating that it's "cleaner", but to me it doesn't really look that way. I much rather see `promise.then().catch()` than async-await wrapped in try-catch clauses. the latter doesn't look cleaner in any way to me.
@JamesQQuick Жыл бұрын
Cleaner is relative. I certainly think it's cleaner, but that's just my opinion. Regardless, you'd have the same issue if you used then/catch. You'd still have to check the response status before trying to parse JSON safely
@mario_luis_dev Жыл бұрын
@@JamesQQuick definitely subjective, that’s why I’ve kept saying “to me”. Those chained promise methods to me look much cleaner than the equivalent code wrapped in try-catch, if-else clauses… Looks more declarative.
@JamesQQuick Жыл бұрын
Fair enough! Whatever works for you. To your original quesiton though, you don't get around having to check statuses when you're using then/catch. Similar logic has to be applied@@mario_luis_dev