Welcome to the first lesson of Efficient API Interactions with Dart. In this course, you will learn how to handle common scenarios when working with APIs more effectively. One of the key aspects of working with APIs is error handling. Handling errors gracefully not only helps in building robust applications but also enhances the user experience by providing meaningful feedback when things go wrong. Our goal in this lesson is to help you manage these outcomes effectively using Dart's http
package.
When you send a request to an API, the server responds with an HTTP status code. These codes indicate the result of your request. Understanding them is essential for effective error handling. Here's a brief overview:
- 2xx (Success): Indicates that the request was successfully received, understood, and accepted. For example, a
200
status code means OK. - 4xx (Client Errors): Suggests that there was an error in the request made by your client. For example,
404
means the requested resource was not found. - 5xx (Server Errors): Indicates that the server failed to fulfill a valid request. A common code here is
500
, which means an internal server error.
By paying attention to these codes, you can determine whether your request succeeded or if there was a problem that needs addressing.
In Dart, you can handle errors by using try-catch blocks, manually checking the status code, and throwing exceptions for bad responses like those with 4xx
and 5xx
status codes.
Consider the following example, which fetches todo items from an API:
Dart1import 'dart:convert'; 2import 'package:http/http.dart' as http; 3 4void main() async { 5 // Base URL for the API 6 final String baseUrl = "http://localhost:8000"; 7 8 try { 9 // Send a GET request to retrieve todos 10 final response = await http.get(Uri.parse('$baseUrl/invalid-route')); 11 12 // Check for bad responses (4xx and 5xx status codes) 13 if (response.statusCode >= 400) { 14 // Attempt to extract error message from the response body 15 String errorMessage = jsonDecode(response.body)['error'] ?? 'Unknown error'; 16 // Throw a ClientException 17 throw http.ClientException(errorMessage); 18 } 19 20 // Parse and print the JSON response 21 List todos = jsonDecode(response.body); 22 print("Todos fetched successfully:"); 23 for (var todo in todos) { 24 print("- ID: ${todo['id']}: ${todo['title']} (Done: ${todo['done']})"); 25 } 26 } on http.ClientException catch (httpErr) { 27 // Print error message 28 print(httpErr.message); 29 } catch (err) { 30 // Handle all other types of exceptions 31 print("Other error occurred: $err"); 32 } 33}
In this example:
-
After making the
GET
request, we check if the status code is4xx
or5xx
. If so, we attempt to extract an error message from the response body and throw anhttp.ClientException
with this message. This approach ensures that any response with a4xx
or5xx
status code is treated as an error. For our API, we assume the error message is JSON-formatted, but it's important to note that some APIs may return plain text error messages instead. -
The try-catch block is used to catch and handle these exceptions, providing detailed error information.
-
Additionally, a generic catch block is included to handle any other types of exceptions that may occur.
When you send a request to an invalid route, the server typically responds with a 404
status code, indicating that the requested resource was not found. In the provided Dart example, this would trigger the http.ClientException
in the try-catch block. Here's how the output might look:
Plain text1404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. at null
This output provides clear feedback that the request failed due to an invalid route, allowing you to diagnose and correct the issue.
In this lesson, you learned about the importance of error handling in API requests and were introduced to effective techniques using HTTP status codes and try-catch blocks in Dart. These practices are crucial for creating robust applications that deal with errors gracefully and provide clear feedback to users.
You are now equipped to practice these skills through hands-on exercises that will reinforce the concepts you've learned. As you move forward, you'll continue to build on these techniques to engage with more advanced API features. Remember, practicing error handling is key — experiment with different scenarios to see how errors are managed and how they affect your applications.
