CHAPTER 4
CONSUMING WEB SERVICES
Consuming Web Services
Error Handling in Service Consumption:
It involves identifying, catching, and responding to failures—such
as timeouts, invalid data, or server errors (e.g., HTTP 404, 500)—
when an application calls an external service or API. Effective
strategies ensure system resilience, prevent application crashes,
and provide meaningful feedback to users or systems, rather than
cryptic technical messages.
Consuming Web Services
Error Handling in Service Consumption
• problems such as :
Connection interruption.
Timeout.
404 Link error.
500 Server error.
Sending incorrect data (Bad Request)
Unauthorized access.
Consuming Web Services
Error Handling in Service Consumption
Therefore, the code should include:
Try/Catch
Clear error messages
Retry logic (retrying again if the request fails)
Status code verification
send a GET request to the API.
If the response is successful
(status code = 200), we read the
JSON.
Error Handling in Service Consumption
� Basic Error Handling
� Handling HTTP Errors (404 / 500 / 401 …)
� Handling Network & Timeout Errors
� Retry Logic + Fallback Handling
1- Basic Error Handling (Try / Catch)
Basic error handling refers to the fundamental use of try…catch blocks
to prevent an application from crashing when something goes wrong
during an external API call.
When consuming external services, many unpredictable issues can
happen:
The API might be down
The internet connection might drop
The response format might change
Your code could throw unexpected errors
Without basic error handling, your application would crash
immediately.
1- Basic Error Handling (Try / Catch)
How it works:
wrap risky code inside a try block.
If anything fails, execution jumps to the catch block.
1- Basic Error Handling (Try / Catch)
Benefit of use:
•Prevents the application from stopping unexpectedly
•Allows you to log the error
•Gives you the option to return a meaningful error message
2- Dealing with response status
codes(HTTP Status Codes)
When connecting to an external API, the following may occur:
• 404 Not Found
• 500 Internal Server Error
• 400 Bad Request
• 401 Unauthorized
2- Dealing with response status
codes(HTTP Status Codes)
Even if the request is successful on the network level, the server
may return an error code.
Common HTTP Status Codes:
How to handle them:
You always check the response’s status code before reading
the content.
2- Dealing with response status codes(HTTP Status Codes)
conclusion:
Always check status codes
Different codes require different actions
Some errors are the user's fault (400), some are the
server’s fault (500)
3- Handling Network Errors & Timeout Errors
These errors occur before the server even sends a response. These
are the most important scenarios in service consumption: Internet
outage, Time out, DNS failure, Server problem.
Types of network errors:
No internet connection
DNS failure
Server unreachable
Request too slow (timeout)
3- Handling Network Errors & Timeout Errors
Exceptions you must handle:
3- Handling Network Errors & Timeout Errors
// Timeout
// Network problems: Internet outage – DNS – Server rejection
3- Handling Network Errors & Timeout Errors
Benefits:
Timeouts prevent the application from waiting
forever
Network errors are common and must be
handled gracefully
Use CancellationTokenSource to enforce
timeout limits
4- Retry Logic & Fallback Handling
Retry Logic Example:
If the connection fails, you can try 3 times again.
4- Retry Logic & Fallback Handling
Fallback Handling
A fallback is what your system does if all retries fail.
Example:
• Return cached data
• Return a default static response
• Return a friendly error message
• Switch to backup API
4- Retry Logic & Fallback Handling
Fallback Example:
Review Question
1. Which of the following best describes error
handling when consuming external APIs?
A. A process to increase API speed
B. A method to prevent any API request from failing
C. A technique to manage failures and unexpected
responses when calling services
D. A way to store API data in the database
2. What HTTP status code indicates that
the requested resource does not exist?
A. 200
B. 401
C. 404
D. 500
3. Which exception is commonly thrown when
the request exceeds the timeout limit?
A. NullReferenceException
B. TaskCanceledException
C. FormatException
D. UnauthorizedAccessException
4. Which type of error occurs when there is no
internet connection or DNS failure?
A. Timeout error
B. HTTP 500
C. HttpRequestException
D. BadRequest
5. Which method is used to verify
if an API response is successful?
A. response.IsOk()
B. response.Status()
C. response.IsSuccessStatusCode
D. response.Success()
6. What should a developer do before reading the response body?
A. Change the URL
B. Validate the status code
C. Restart the API
D. None of the above
7. What does a 500 status code represent?
A. Client error
B. Successful request
C. Authentication error
D. Server-side error
8. Which technique allows the application to try calling an API again if
the first attempt fails?
A. Filtering
B. Retrying
C. Logging
D. Serialization
9. Which block is required to write code that handles exceptions?
A. switch
B. try…catch
C. for loop
D. if…else
10. Which of the following errors is MOST likely caused by invalid
request parameters?
A. 500
B. 404
C. 400
D. Timeout