I am working on a tauri application and I would like to be able to return a struct to the frontend with a message and severity from 0-2
.
{
"msg": "some error message",
"severity": 1,
}
I'd like to be able to do this elegantly and ideally I would be able to utilise the question mark operator for clean error handling like so:
#[tauri::command]
fn my_command() -> MyCustomResult {
let some_result = error_prone_function();
convert_result(some_result, Severity::Medium)?;
}
If possible, what would be the cleanest way of doing this? Otherwise, what is the best alternative?
Basically the only requirement is that your error must implement serde::Serialize
. Tauri's docs give a small introduction/example maybe that's enough to give you an idea: https://tauri.app/v1/guides/features/command#error-handling
An example based on something i use myself could look like this:
impl serde::Serialize for Error {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("Error", 2)?;
state.serialize_field("severity", &self.severity())?;
state.serialize_field("message", &self.to_string())?;
state.end()
}
}