英文:
How to return a custom error struct with results?
问题
以下是翻译好的部分:
{
"msg": "一些错误消息",
"severity": 1
}
#[tauri::command]
fn my_command() -> MyCustomResult {
let some_result = error_prone_function();
convert_result(some_result, Severity::Medium)?;
}
英文:
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?
答案1
得分: 0
基本上唯一的要求是你的错误类型必须实现serde::Serialize
。Tauri的文档提供了一个小的介绍/示例,也许这足以给你一个思路:https://tauri.app/v1/guides/features/command#error-handling
一个基于我自己使用的示例(https://github.com/FabianLars/mw-toolbox/blob/a528144e21cdf6cb4969fa745461ab8943c4cc86/crates/mw-tools/src/error.rs#L72-L84)可能是这样的:
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()
}
}
英文:
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()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论