Handling Errors | Lecture 144 | React.JS 🔥

The Coding Classroom
11 Dec 202313:03

Summary

TLDRThe video script focuses on error handling in web applications, particularly when dealing with asynchronous data fetching. It emphasizes the importance of being prepared for potential issues such as loss of internet connection or API errors. The tutorial demonstrates how to simulate and handle these scenarios by using try-catch blocks in JavaScript, updating application states to reflect errors, and displaying user-friendly error messages. It also introduces a state variable to manage error messages and conditional rendering to ensure a smooth user experience, even when data fetching fails.

Takeaways

  • 🔍 Always assume errors can occur when dealing with asynchronous data in web applications.
  • 💻 Simulate network issues like loss of internet connection to test error handling.
  • 📶 Check the network tab to ensure the application behaves correctly under slow or offline conditions.
  • 🛑 Use try-catch blocks to handle errors manually, as fetch does not inherently react to errors.
  • 📌 Check the response object's `ok` property to determine if the response is successful or not.
  • 🔁 Throw new errors when the response is not okay to handle specific error cases.
  • 🔄 Use a finally block to ensure certain code is executed regardless of whether an error occurred.
  • 📋 Maintain a separate state variable to track and display error messages.
  • 📝 Log error messages to the console for debugging purposes.
  • 🎨 Create a simple presentational component to display error messages with appropriate styling.
  • 🔄 Ensure that the application's loading, error, and data display states are mutually exclusive.

Q & A

  • Why is it important to handle errors during data fetching in web applications?

    -It is important to handle errors to provide a better user experience by informing users of issues, such as a lost internet connection, and to avoid leaving the application in a perpetual loading state.

  • How can you simulate a lost internet connection in a web application for testing purposes?

    -You can simulate a lost internet connection by using the network tab in the browser's developer tools to set the connection to 'offline' while data is loading.

  • What does the 'response.ok' property signify in the context of fetch requests in JavaScript?

    -The 'response.ok' property indicates whether the response was successful (status in the range 200-299) or not, helping to identify request failures.

  • What should you do in JavaScript code if the 'response.ok' property is false?

    -If 'response.ok' is false, you should throw a new error to indicate that something went wrong with the fetch request.

  • What is the purpose of using a try-catch block in JavaScript?

    -A try-catch block is used to catch errors in a section of code, allowing developers to handle exceptions and prevent the application from crashing.

  • Why is conditional rendering used in web applications?

    -Conditional rendering is used to display different components or elements based on certain conditions, such as loading states or the presence of errors, enhancing user experience.

  • How can you manage the loading state in a React application to handle asynchronous data fetching?

    -In a React application, you manage the loading state by using state variables to indicate when data is being fetched and then updating these variables appropriately to reflect when loading is complete or an error occurs.

  • What is the significance of the 'finally' block in error handling in JavaScript?

    -The 'finally' block is executed after the try and catch blocks, regardless of the result, allowing for cleanup actions or resetting states like the loading state, ensuring code runs even after an error.

  • How can the absence of data from an API be handled in a web application?

    -The absence of data can be handled by checking the received data and throwing an error or displaying a specific message if the expected data is undefined or does not meet required conditions.

  • Why is it important to handle different types of errors separately in web applications?

    -Handling different types of errors separately allows for more tailored user feedback and specific troubleshooting steps, improving the overall user experience and application reliability.

Outlines

00:00

🔍 Error Handling in Data Fetching

This paragraph discusses the importance of error handling when fetching data in web applications, especially with asynchronous data. It highlights the need to account for scenarios such as users losing internet connection. The speaker simulates this by switching to slow 3G and then to offline mode, demonstrating how the application should not remain in a loading state indefinitely. The script explains how to handle errors by checking the response object from the fetch function and throwing a new error if the response is not okay. It also introduces the use of a try-catch block to handle errors and the creation of a new error component to display error messages on the screen.

05:03

📊 Conditional Rendering for Error Display

The second paragraph focuses on the implementation of conditional rendering to display error messages or movie lists based on the application's state. It explains the process of nesting ternary operators to manage different states such as loading, error, and no data. The speaker emphasizes the importance of ensuring that only one of the three mutually exclusive conditions (loading, error, or no data) is true at any given time to avoid displaying multiple components simultaneously. The paragraph also addresses the issue of the loading state remaining true even after an error is thrown and suggests using a finally block to ensure that the loading state is reset.

10:08

🛠️ Handling API Response Errors

The third paragraph delves into handling errors that arise from API responses, such as when no movies are found for a search query. It demonstrates how to check the API response for faults and throw a new error with a custom message like 'movie not found'. The speaker recaps the process of setting an error state and using it for conditional rendering on the UI. The paragraph concludes by stressing the significance of error handling in web applications, which is often overlooked but is essential for a smooth user experience.

Mindmap

Keywords

💡asynchronous data

Asynchronous data refers to data that is fetched or processed independently of the main thread of execution, often in web applications. This allows for non-blocking operations, such as fetching data from a server while the user continues to interact with the application. In the video, handling asynchronous data is crucial for ensuring a smooth user experience, especially when dealing with potential errors like lost internet connections.

💡error handling

Error handling is the process of responding to the occurrence, in a computer program, of an event that disrupts the normal flow of instructions. It is a fundamental part of software development, ensuring that the application can recover gracefully from unexpected conditions. In the context of the video, error handling involves displaying error messages to the user when data fetching fails, such as when the user is offline.

💡fetch function

The fetch function is a web API that provides an easy, logical way to fetch resources asynchronously across the network. It returns a Promise that resolves to the Response to that request, whether it is successful or not. In the video, the fetch function is used to retrieve data from a server, and its usage is crucial for handling asynchronous data in web applications.

💡try-catch block

A try-catch block is a control flow statement in JavaScript that allows code to be written in a way that can handle exceptions. The try block contains the code that might throw an exception, and the catch block is executed if an exception is thrown. This is a standard JavaScript feature used for error handling, as demonstrated in the video when wrapping the fetch operation to handle potential errors.

💡state management

State management in web applications refers to the process of managing the state (data) of an application over time. This is essential for maintaining the user's experience, especially in dynamic applications where data can change frequently. In the video, state management is used to track whether there is an error, and to conditionally render the UI based on the application's state.

💡conditional rendering

Conditional rendering is a technique in web development where the UI is dynamically generated based on certain conditions. This allows for a more responsive and interactive user interface. In the video, conditional rendering is used to display different components depending on whether the application is loading, has an error, or is ready to display the content.

💡API response

An API response is the data returned by an application programming interface (API) after a request has been made. It typically includes a status code, headers, and a body containing the data. In the video, the API response is checked for errors, and the application's behavior is adjusted based on the response.

💡React

React is a JavaScript library for building user interfaces, particularly useful for creating single-page applications. It allows developers to create reusable UI components and manage their state in a declarative manner. The video discusses React in the context of error handling and state management within a React application.

💡finally block

A finally block is part of the try-catch-finally statement in JavaScript, which is executed regardless of whether an exception was thrown or caught. It is used for cleanup code that should run no matter what the outcome of the try block is. In the video, a finally block is suggested to ensure that certain code is executed even after an error is thrown.

💡ternary operator

The ternary operator is a shorthand for an if-else statement in JavaScript. It takes three operands: a condition followed by a result for true and a result for false. It is often used for concise conditional assignments. In the video, the ternary operator is mentioned in the context of conditional rendering within the application.

💡presentational component

A presentational component in React is a component that is concerned only with how things look, without any logic or state management. It is a pure function of its props, receiving data and returning a UI representation. In the video, an error message component is created as a simple presentational component.

Highlights

Assuming errors in web applications dealing with asynchronous data is crucial.

Simulating a user losing internet connection to test error handling.

Using a try-catch block to handle errors in JavaScript.

Checking the response object's 'ok' property to determine if an error occurred.

Throwing a new error when the response is not okay.

Displaying an error message on the screen instead of keeping the application in a loading state.

Creating a new state variable to indicate the presence of an error.

Using conditional rendering to display the error message component when an error exists.

Creating an error message component to display error messages with an emoji.

Handling situations where the API response is undefined or an empty array.

Throwing an error when no movies are found for a search query.

Using a finally block to ensure the loading state is reset after an error.

Ensuring that the error, loading, and data display conditions are mutually exclusive.

Reacting to errors is not built into the fetch function and must be handled manually.

The importance of error handling in web applications, which is often overlooked but essential.

Analyzing the code after the video to understand the conditions and error handling logic.

Transcripts

play00:01

‫So whenever we are doing any data fetching

play00:03

‫in any web application

play00:05

‫and dealing with asynchronous data,

play00:08

‫we always need to assume that something can go wrong.

play00:12

‫And so therefore, let's now account

play00:14

‫for that situation by handling those errors.

play00:19

‫So one of the things that can go wrong

play00:22

‫is your users suddenly losing their internet connection.

play00:26

‫So let's simulate that here again in our network tab

play00:29

‫and let's make sure that we are first on slow 3G.

play00:33

‫Then let's reload here, and then

play00:36

‫while the movies are loaded, we will click on offline.

play00:40

‫So right now,

play00:42

‫so you see that now the application

play00:44

‫basically never leaves the state.

play00:47

‫And also when we come to our console here we see

play00:50

‫that we failed to fetch,

play00:53

‫which again is because our user basically now

play00:56

‫lost their internet connection.

play00:59

‫So when that happens, we want to display some kind

play01:02

‫of error message here on the screen and not

play01:05

‫keep the application in this loading state here forever.

play01:09

‫Because like this, the user will think

play01:11

‫that the data might eventually arrive

play01:14

‫but of course it will not.

play01:16

‫Now, reacting to errors like this is actually not built

play01:21

‫into the fetch function itself.

play01:24

‫And so we have to kind of do that manually.

play01:26

‫And so let's try that here in our fetch movies function.

play01:32

‫So here on the response object

play01:35

‫that we receive from fetch exists one, okay, property.

play01:41

‫And so here we can check for that.

play01:43

‫So basically if the response is not okay

play01:46

‫then we want to throw a new error.

play01:49

‫And again, this is pretty standard JavaScript code.

play01:53

‫So then let's just say something went wrong

play02:00

‫with fetching movies now, okay?

play02:04

‫And so now if we throw an error here

play02:06

‫we need to wrap all of our code into a try catch block. So,

play02:13

‫try and catch

play02:17

‫which again is just a normal JavaScript feature.

play02:20

‫This one has nothing to do with React.

play02:23

‫Okay, and here let's console that error.

play02:28

‫That error, okay?

play02:32

‫And then let's come back here.

play02:35

‫Well, if we load now, then of course nothing will work.

play02:40

‫So let's do that trick again where first

play02:41

‫we set it to slow 3G,

play02:44

‫then let's reload and then let's wait for it.

play02:49

‫We set our users back to offline right now.

play02:55

‫And so where is it?

play02:59

‫Well, it's not actually anywhere here,

play03:02

‫but well, that's not really important anyway.

play03:05

‫So let's actually just log error dot message.

play03:10

‫So this is the property of the error

play03:12

‫where this string here will get saved into

play03:16

‫but then what we're actually interested in,

play03:19

‫is to get this message here onto the screen.

play03:23

‫So basically displaying it right here instead of loading.

play03:27

‫So that means that we need another piece of state.

play03:31

‫So basically a piece of state indicating

play03:33

‫whether we currently have an error or not.

play03:39

‫So const error

play03:42

‫and set error.

play03:47

‫And so here, this one is actually not a bullion,

play03:49

‫but it's truly the error message.

play03:53

‫Okay, so here

play03:56

‫let's then set the error

play03:59

‫to actually that message.

play04:01

‫And again, error dot message is basically

play04:04

‫this string that we passed into the error

play04:07

‫and error is the error itself

play04:09

‫as it was passed into this catch block.

play04:12

‫And again, that is just basic JavaScript.

play04:15

‫All right,

play04:17

‫and then let's do some conditional rendering here

play04:20

‫to basically get the error here

play04:23

‫onto the screen whenever there exists one.

play04:28

‫Now, okay, and let's start

play04:29

‫by creating a new error component here

play04:33

‫or maybe let's call it error message.

play04:36

‫And it will receive a prop

play04:39

‫with some message that it will then display on the screen.

play04:46

‫So let's return again a paragraph this time

play04:49

‫with the class name of error, which,

play04:52

‫as always, I already included into my CSS file.

play04:58

‫Then here let's maybe add some small emoji here,

play05:02

‫like this one.

play05:05

‫So showing there was some kind of problem.

play05:10

‫And then here we simply display that message.

play05:13

‫So this is a very simple presentational component.

play05:17

‫Remember that?

play05:21

‫Okay. Now here in our conditional rendering

play05:24

‫basically what we want to do is

play05:27

‫that when it's no longer loading

play05:29

‫then we want to display this movie list

play05:32

‫but only if there was no error.

play05:35

‫So basically here we now would have to nest another ternary

play05:38

‫inside this ternary, but that makes for really ugly coat.

play05:43

‫And so let's do something else instead.

play05:46

‫So let's comment out this entire part.

play05:51

‫Or well, only this one.

play05:54

‫So the box of course we still need,

play05:57

‫but then let's do is loading.

play06:01

‫And if there's no error

play06:06

‫then display this movies list right here.

play06:12

‫Now if there is an error

play06:17

‫then display the error message component

play06:20

‫with the error or I think it's called message.

play06:25

‫So with the message prop set to error.

play06:30

‫And here of course, it needs to be

play06:32

‫that the data is not loading and there is no error.

play06:36

‫And finally, we also need to account

play06:39

‫of course for the is loading state.

play06:43

‫So if it is loading, then just display our loader.

play06:49

‫So here the situation is indeed a little bit tricky

play06:52

‫with all these different states that we have

play06:55

‫and with all the conditional rendering, but well

play06:58

‫these are now three mutually exclusive conditions.

play07:03

‫So it is either loading or it is not loading

play07:06

‫and there is no error or there is an error.

play07:09

‫So only one of these three here

play07:11

‫can be true at the same time.

play07:13

‫And so that's very important

play07:14

‫so that we don't display multiple

play07:16

‫of these components at the same time by mistake.

play07:20

‫So let's give it a save and let's try again.

play07:25

‫So back to our 3G

play07:30

‫and then I will set it to offline very soon.

play07:34

‫Let's wait for it.

play07:41

‫And there it is.

play07:43

‫So we get our error message correctly displayed here.

play07:46

‫However, there's still some problem

play07:48

‫because the loading state is still set to true

play07:53

‫and in fact that's actually correct.

play07:57

‫So as soon as the error here is thrown,

play08:00

‫this rest of the code is no longer evaluated.

play08:03

‫And so therefore is loading is never set to fault.

play08:07

‫So our application will keep thinking

play08:09

‫that the data is still being loaded.

play08:12

‫So again, the problem is

play08:14

‫that after this error is being thrown

play08:16

‫then React will basically never see

play08:19

‫this piece of code here,

play08:21

‫where the loading state is reset.

play08:24

‫So instead of doing that here

play08:26

‫let's attach a finally block here.

play08:30

‫So this block of code here will basically always be executed

play08:35

‫at the very end.

play08:38

‫Okay? And as an alternative

play08:41

‫we could have kept the code here and also pasted it here,

play08:45

‫but that would've created a duplication of code.

play08:48

‫So with this, it's going to be a lot better.

play08:51

‫Now, I will not try this yet here

play08:53

‫because actually I want to handle another kind of error

play08:57

‫which is not really an error,

play08:59

‫but also situation where we want to display a message

play09:02

‫which is the situation

play09:04

‫in which we cannot find any movie for the search Query.

play09:09

‫So let's say the Query is like this one here

play09:12

‫and of course the API will not find anything.

play09:17

‫So let's remove all throttling,

play09:21

‫and well, what happens here?

play09:29

‫Well, basically the length cannot be read of undefined.

play09:32

‫And so the problem here is that the data

play09:35

‫that comes back from the API now,

play09:37

‫is apparently undefined.

play09:41

‫So let's take a look at that.

play09:43

‫So just at data here, and let's try that again.

play09:48

‫And so indeed, we no longer have the search property here,

play09:54

‫so we no longer have data dot search.

play09:57

‫And so what's happening then is that data search

play10:00

‫is being set to undefined,

play10:02

‫and therefore we get this other error here.

play10:08

‫So as I was saying in the very beginning

play10:10

‫we always need to handle

play10:11

‫all these different situations that can go wrong.

play10:14

‫And when we are working with data fetching

play10:17

‫there's always a lot of things that can go wrong.

play10:21

‫So working with data is a lot of work

play10:23

‫but it's also essential in most

play10:26

‫if not all web applications.

play10:29

‫But anyway, here we can now use this response

play10:33

‫to our advantage,

play10:34

‫in order to throw another error in this situation.

play10:38

‫So we can say that data dot response,

play10:43

‫and actually, this now needs to be here

play10:46

‫after we already have the data.

play10:50

‫So in this case, if data responds is equal faults

play10:56

‫and so for some reason the API here responds

play10:59

‫with the string of faults and not a bullion

play11:03

‫but while this still works, so in this case, let's

play11:07

‫also throw a new error and let's simply say

play11:11

‫movie not found.

play11:16

‫Alright, and beautiful.

play11:20

‫Let's just reload.

play11:22

‫And then here we get this log.

play11:24

‫So that's this console dot error coming from here.

play11:27

‫And then indeed we get our error message also displayed

play11:30

‫on the UI.

play11:32

‫So this one was maybe a little bit trickier.

play11:35

‫So let's just quickly recap.

play11:38

‫So what we did was to implement another state variable,

play11:41

‫this time, specific for the error

play11:44

‫so that whenever some error occurred

play11:46

‫we could store the error message in there

play11:49

‫and then display it in the UI as soon as an error occurred.

play11:53

‫Now, as soon as an error did occur, which is

play11:57

‫in this situation, and in this one we threw a new error,

play12:01

‫and then we caught that error

play12:03

‫inside the catch block of this try-catch.

play12:07

‫And so this is a standard way

play12:08

‫of catching errors in JavaScript.

play12:11

‫And so in this situation, we then set the error state

play12:15

‫to the message of the error that we specified here.

play12:18

‫Then finally, we used of course, that state variable

play12:22

‫in order to render something on the screen conditionally.

play12:26

‫And so that was right here.

play12:29

‫So this part here is maybe a bit confusing.

play12:32

‫And so make sure that after this video you just

play12:34

‫analyze exactly what's happening here and that,

play12:37

‫in fact these three conditions here are mutually exclusive.

play12:41

‫So only one of them will ever be true.

play12:44

‫Okay? And I think that for now this is enough

play12:47

‫for error handling in this application.

play12:50

‫So that's always a very,

play12:52

‫very important part that many people overlook.

play12:55

‫But it is of course essential

play12:57

‫to deal with these kind of situations.

Rate This

5.0 / 5 (0 votes)

Related Tags
Error HandlingWeb DevelopmentAsynchronous DataUser ExperienceJavaScriptFetch APINetwork SimulationTry-CatchConditional RenderingState ManagementWeb Performance