async-graphql/docs/zh-CN/src/error_handling.md
Edward Rudd 3b7ed74d11 correct doc examples so they compile
- examples to fix still
  - error_extensions.md ResultExt example does not compile!
     - trait ErrorExtensions is not implemented for ParseIntError
  - dataloader
     - requires sqlx to work. So we either "stub" it OR we rewrite them simpler to use a  simple "faux" db library
2022-06-02 17:32:12 -04:00

730 B
Raw Blame History

错误处理

Resolver函数可以返回一个Result类型以下是Result的定义

type Result<T> = std::result::Result<T, Error>;

任何错误都能够被转换为Error,并且你还能扩展标准的错误信息。

下面是一个例子,解析一个输入的字符串到整数,当解析失败时返回错误,并且附加额外的错误信息。

# extern crate async_graphql;
# use std::num::ParseIntError;
use async_graphql::*;

struct Query;

#[Object]
impl Query {
    async fn parse_with_extensions(&self, input: String) -> Result<i32> {
        Ok("234a"
            .parse()
            .map_err(|err: ParseIntError| err.extend_with(|_, e| e.set("code", 400)))?)
    }
}