如何在Rust serde序列化器中传播错误?

wi3ka0sx  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(120)

我正在尝试实现serde的serialize_with属性。
我有这个代码:

use serde::Serializer;

pub fn serialize_json_as_string<S>(json: &serde_json::value::Value, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let string = serde_json::to_string(json).unwrap();
    s.serialize_str(&string)
}

我不喜欢倒数第二行的unwrap()。但是我不知道如何将to_string返回的错误转换为S::Error
我试着用如下代码替换let行:

let string = serde_json::to_string(json)?;

我得到了:

error[E0277]: `?` couldn't convert the error to `<S as serde::Serializer>::Error`
  --> src/model/field_type.rs:30:45
   |
26 | pub fn serialize_json_as_string<S>(json: &serde_json::value::Value, s: S) -> Result<S::Ok, S::Error>
   |                                                                              ----------------------- expected `<S as serde::Serializer>::Error` because of this
...
30 |     let string = serde_json::to_string(json)?;
   |                                             ^ the trait `From<serde_json::Error>` is not implemented for `<S as serde::Serializer>::Error`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = note: required for `Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>` to implement `FromResidual<Result<Infallible, serde_json::Error>>`
help: consider further restricting the associated type
   |
28 |     S: Serializer, <S as serde::Serializer>::Error: From<serde_json::Error>
   |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For more information about this error, try `rustc --explain E0277`.

我也试着用以下内容来代替:

match serde_json::to_string(json) {
   Ok(string) => s.serialize_str(&string),
   Err(e) => Err(e.into()),
}

类似错误:

error[E0277]: the trait bound `<S as serde::Serializer>::Error: From<serde_json::Error>` is not satisfied
  --> src/model/field_type.rs:32:25
   |
32 |         Err(e) => Err(e.into()),
   |                         ^^^^ the trait `From<serde_json::Error>` is not implemented for `<S as serde::Serializer>::Error`
   |
   = note: required for `serde_json::Error` to implement `Into<<S as serde::Serializer>::Error>`
help: consider further restricting the associated type
   |
28 |     S: Serializer, <S as serde::Serializer>::Error: From<serde_json::Error>
   |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For more information about this error, try `rustc --explain E0277`.

由于我没有Serde,我假设我不能实现into,所以我需要某种手动转换。我不知道那会是什么样子。

soat7uwm

soat7uwm1#

该错误不是serde错误,但您可以将其 Package 在serde自定义错误中,如下所示:

use serde::{Serializer, ser::Error};

pub fn serialize_json_as_string<S>(json: &serde_json::value::Value, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let string = serde_json::to_string(json).map_err(S::Error::custom)?;
    s.serialize_str(&string)
}

请注意,您需要导入serde::ser::Error,因为这是custom函数的trait来源。

相关问题