Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Built in error type that cannot be handled and just contains a message?

Is there a built in error type that just prints a message, but cannot do anything else? I don’t need to be able to know what the error is, I just want to print it to a log file. It will effectively be a silent panic, since the error is one severity down from ‘unrecoverable’.

The error signifies that a bug has occurred, but since it will run on a persistent server, I just need to interrupt the task that’s running, rather than the whole process. The rest of the code can recover from this, but not the task.

I would like to do the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use ...::SomeError;

fn some_operation() -> Result<i32, impl Error> {
  let value: Option<i32> = /*some fallible operation that will work if there's no bug*/;
  value.ok_or_else(|| SomeError::new("Something just happened that probably shouldn't have".to_string()))
}

I know I can define a custom error type to do this, but I’d like to use a builtin if there’s one defined.

>Solution :

String and &str implement Into<Box<dyn Error + Send + Sync>>, so you can just use that directly:

fn some_operation() -> Result<i32, Box<dyn std::error::Error + Send + Sync>> {
    let value: Option<i32> = /*some fallible operation that will work if there's no bug*/;
    Ok(value.ok_or("Something just happened that probably shouldn't have")?)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading