如何返回带有自定义错误结构的结果?

huangapple go评论67阅读模式
英文:

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&lt;S&gt;(&amp;self, serializer: S) -&gt; Result&lt;S::Ok, S::Error&gt;
    where
        S: serde::ser::Serializer,
    {
        use serde::ser::SerializeStruct;

        let mut state = serializer.serialize_struct(&quot;Error&quot;, 2)?;
        state.serialize_field(&quot;severity&quot;, &amp;self.severity())?;
        state.serialize_field(&quot;message&quot;, &amp;self.to_string())?;
        state.end()
    }
}

huangapple
  • 本文由 发表于 2023年2月8日 16:25:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定