阿波罗服务器上的formatError

时间:2020-06-11 00:11:09

标签: typescript

您好,我正在尝试在graphql apollo服务器中设置错误格式 到目前为止,我有这个结构:

{
  "errors": [
    {
      "type": "Unprocessable Entity",
      "message": "Validation Failed",
      "code": 422,
      "errors": [
        {
          "field": "email",
          "code": "invalid_field"
        },
        {
          "field": "name",
          "code": "invalid_field"
        }
      ]
    }
  ],
  "data": null
}

这是我的代码:

    formatError: (error) => {
      const { originalError } = error;
      if (isSpiritErrorInstance(originalError)) {
        // log internalData to stdout but not include it in the formattedError
        console.log();
      }
      return formatApolloError(error);
    },
    debug: false,
  });

我的自定义类错误:

export interface fooBar_error {
  foo: string;
  bar: string;
}
interface missing_field {
  field: string;
  code: string;
}
/*Default Errors */
export interface ErrorConfig {
  type?: string;
  message: string;
  errors?: missing_field[] | fooBar_error[];
  code: number;
}

const isString = (d) => Object.prototype.toString.call(d) === '[object String]';
const isObject = (d) => Object.prototype.toString.call(d) === '[object Object]';
/* Base Error */
export class BaseError extends ExtendableError {
  type: string;
  message: string;
  code: number;
  errors?: missing_field[] | fooBar_error[];

  constructor(args: ErrorConfig) {
    super(args.message || '');
    const type = args.type;
    const message = args.message;
    const code = args.code;
    const error = args.errors;
    this.type = type;
    this.message = message;
    this.code = code;
    this.errors = error;
  }
  serialize(): ErrorConfig {
    const { type, message, code, errors } = this;
    let error: ErrorConfig = {
      type,
      message,
      code,
      errors,
    };
    return error;
  }
}
/* is Instance */
export const isInstance = (e) => e instanceof BaseError;

/* Unprocessable Entity Error */
export class UnprocessableEntityERROR extends BaseError {
  errors: missing_field[];
  constructor(error: missing_field[]) {
    super({
      type: 'Unprocessable Entity',
      message: 'Validation Failed',
      code: 422,
    });
    this.errors = error;
  }
}

export const formatError = (error, returnNull = false): ErrorConfig => {
  const originalError = error ? error.originalError || error : null;
  if (!originalError) return returnNull ? null : error;

  const { type } = originalError;

  if (!type || !isInstance(originalError)) return returnNull ? null : error;

  const { message, code, errors } = originalError;

  return originalError.serialize();
};

我只想知道这种错误结构:

{
  "type": "Unprocessable Entity",
  "message": "Validation Failed",
  "code": 422,
  "errors": [
    {
      "field": "email",
      "code": "invalid_field"
    },
    {
      "field": "name",
      "code": "invalid_field"
    }
  ]
}

我已经尝试将格式错误的返回值更改为:

返回{类型,消息,代码,错误}

我不知道该怎么办: “错误”数组

0 个答案:

没有答案