w3resource

Rust Function for Network Requests: Fetch data or Handle error

Rust Handling Errors with Result and Option: Exercise-9 with Solution

Write a Rust function that performs network requests, returning data or an error if the request fails.

Sample Solution:

Rust Code:

use reqwest; // Import the reqwest crate for making HTTP requests
use std::error::Error; // Import the Error trait for error handling

// Function to perform a GET request to the specified URL and return the response body
fn fetch_data(url: &str) -> Result<String, Box<dyn Error>> {
    let response = reqwest::blocking::get(url)?; // Perform the GET request and handle any errors
    
    // Check if the request was successful (status code 200 OK)
    if response.status().is_success() {
        let body = response.text()?; // Extract the response body as a string
        Ok(body) // Return the response body
    } else {
        Err(format!("Request failed with status code: {}", response.status()).into()) // Return an error message if the request was not successful
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let url = "https://api.example.com/data"; // Specify the URL to make the request to
    
    match fetch_data(url) {
        Ok(data) => println!("Received data: {}", data), // Print the received data if the request was successful
        Err(err) => eprintln!("Error fetching data: {}", err), // Print an error message if the request failed
    }

    Ok(()) // Return Ok if the program completes successfully
}

Output:

Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 3.70s
     Running `target/debug/playground`
Error fetching data: error sending request for url (https://api.example.com/data): error trying to connect: dns error: failed to lookup address information: Temporary failure in name resolution

Explanation:

The above code defines a Rust function "fetch_data()" that performs a GET request to a specified URL using the "reqwest" crate. The function returns either the response body as a string or an error if the request fails. The "main()" function demonstrates the usage of 'fetch_data' by making a request to a sample URL and printing the received data or an error message.

Rust Code Editor:

Previous: Rust Function for Network Requests: Fetch data or handle Errors.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/error_handling/rust-handling-errors-with-result-and-option-exercise-9.php