Raising chrono::format::ParseError issue

Hi friends,

I'm still learning and encountering some difficulties, particularly with error handling as a fresh Ruster. Here's a specific issue, feel free to point out if I shouldn't design the function in this way at very beginning.

Currently, I'm working on a function that converts an epoch timestamp to a date and time representation. The code itself works fine without error handling, but I would like to incorporate proper error handling into the function.

Here's my code, it's really simple, with chrono = "0.4".

use chrono::{DateTime, NaiveDateTime, Utc, Local, ParseError};

fn convert_epoch_to_date(epoch_ms: u64) -> Result<String, ParseError> {
    let seconds = epoch_ms / 1000;
    let nanoseconds = (epoch_ms % 1000) * 1_000_000;
    let naive_datetime = NaiveDateTime::from_timestamp_opt(seconds as i64, nanoseconds as u32)
        .ok_or_else(|| chrono::format::ParseError::from("Invalid datetime"))?;

    let datetime: DateTime<Utc> = DateTime::from_utc(naive_datetime, Utc);
    let local_datetime: DateTime<Local> = datetime.into();

    Ok(local_datetime.format("%Y-%m-%d %H:%M:%S%.3f").to_string())
}

fn main() {
    let epoch_ms: u64 = 1677976156123;
    match convert_epoch_to_date(epoch_ms) {
        Ok(date_string) => println!("{}", date_string),
        Err(err) => eprintln!("Error: {}", err),
    }
}

But when I compiled it, I got the error:

error[E0308]: mismatched types
   --> src/test_chrono.rs:7:57
    |
7   |         .ok_or_else(|| chrono::format::ParseError::from("Invalid datetime"))?;
    |                        -------------------------------- ^^^^^^^^^^^^^^^^^^ expected `ParseError`, found `&str`
    |                        |
    |                        arguments to this function are incorrect
    |

I would greatly appreciate it if someone could provide guidance on how to handle this error and properly convert a string to chrono::format::ParseError. I got the document for chrono ParseError in chrono::format - Rust but I did not get it.

Thank you all for your support and assistance!

chrono::format::ParseError does not have a public interface for constructing it. It can only be constructed by chrono itself, not by your crate. I'd suggest creating your own error type (easily done with thiserror) or use a crate like anyhow for handling errors.

2 Likes

got it. Thanks jofas! Other ppl also said that it was better to create own error type. I'll try to do that. Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.