w3resource

Rust Function for Network Requests: Fetch data or handle Errors

Rust Handling Errors with Result and Option: Exercise-8 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.22s
     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:

Here's a brief explanation of the above Rust code:

  • Imports the "reqwest" crate for making HTTP requests and the 'Error' trait for error handling.
  • Define a function "fetch_data()" that takes a URL as input and returns either the response body as a string or an error if the request fails.
    • Inside the function:
      • It performs a blocking GET request to the specified URL using reqwest::blocking::get(url).
      • If the request is successful (status code 200 OK), it extracts the response body as a string using response.text()? and returns it.
      • If the request is not successful (status code other than 200 OK), it returns an error message indicating failure.
  • Defines the "main()" function, which serves as the entry point of the program.
    • Inside the main function:
      • It specifies the URL to make the request to.
      • It calls the "fetch_data()" function with the URL and matches on the result.
      • If the request is successful, it prints the received data.
      • If the request fails, it prints an error message.
  • Returns Ok(()) at the end of the "main()" function to indicate successful program execution./li>.

Rust Code Editor:

Previous: Rust JSON Parsing Program: Read, Parse, and Print Specific data.
Next: Rust Function for Network Requests: Fetch data or Handle error.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.