Loading
Current section: Network 7 exercises
solution

Network errors

Loading solution

Transcript

00:00 In its current state, my getAuthToken function doesn't even handle request promise rejections. I will fix that by adding the catch handler that accepts an error, and instead will throw a more nicer error for me, letting me know that authentication failed due to a network error.

00:17 I will store the reference to the original error as the value of the cost property. This way, whenever this error happens, it will be much nicer to debug, or be able to see what originated that error. Now that I have this catch logic, I need to test it. And for that, I need to somehow reproduce this request promise rejecting in tests. I will do precisely that.

00:36 I will head to the test file, and in this test case for network errors, I will add a new runtime request handler using server.use. I will describe the same handler here for my POST request, but in the resolver, I will not return any responses. Instead, I will return a special response, response.error.

00:56 This is also a standard API. This is a shorthand to create what is effectively a network error, or request error if you would. So what I'm doing here is telling MSW, whenever this POST request happens within this test, emulate the request promise as failing, as rejecting.

01:12 Now all that's left to do is to describe the intention, what I expect to happen. I will copy it from here, and state that whenever the request promise rejects, I want to throw this particular error. I will verify that by running tests, npm test, and I will see this network error scenario

01:31 passing. So what I'm doing here is forcing this request promise to reject, so I'm able to tap into this particular catch logic to make sure that my function is able to handle promise rejections and request failures for whatever reason, and I have an automated test to prove that.