项目开发中,咱们须要经过具体的error信息来告知前端如何处理报错逻辑,好比登陆过时,须要前端退出登陆,清除登陆token等html
最近在找一个关于error上报的问题,把看到的一些资料整理了一下前端
项目架构: 前端使用GATSBY框架,server由于配合的是 koa, 因此主要使用的是 apollo-server-koanode
graphql 中的 GraphQLError 继承自 node的Error类架构
class GraphQLError extends Error { constructor( message: string, nodes?: ReadonlyArray<ASTNode> | ASTNode | undefined, source?: Maybe<Source>, positions?: Maybe<ReadonlyArray<number>>, path?: Maybe<ReadonlyArray<string | number>>, originalError?: Maybe<Error>, extensions?: Maybe<{ [key: string]: any }>, ) --- the rest code --- }
ApolloError 继承自Error 按照GraphQLError 的定义实现app
// class ApolloError extends Error implements GraphQLError { class ApolloError extends Error { constructor(message, code, properties) { super(message); if (properties) { Object.keys(properties).forEach(key => { this[key] = properties[key]; }); } if (!this.name) { Object.defineProperty(this, 'name', { value: 'ApolloError' }); } this.extensions = { code }; } }
ApolloError 可接受三个参数,message, code, properties 框架
前端根据server定义的不一样的code来处理不一样的逻辑koa
switch (code) { case 'WYB': alert('无感') break; default: alert('无羁') break; }
堆栈跟踪
在前端页面咱们log出error信息,能够看到此参数,这个就相似 error.stack 的堆栈跟踪this
每一行都以 "at " 开头。 每一帧描述了一个代码中致使错误生成的调用点spa
若是不想进行错误帧上报,能够在applo-serve中关闭debug
new ApolloServer ({ debug: false })
格式化ERROR
若是须要批量处理error信息,能够在此方法中操做。好比添加error日志警告功能等
new ApolloServer ({ formatError: err => { console.log('请进行错误日志上报') return err } })
这里能够改写error,好比添加一些属性,也能够直接返回error
apollo 有帮助咱们建立了几种常见的Error对象,可在不一样的业务场景中使用,他们全都是继承自 ApolloError ,只不过是将 name 属性从新命名
身份验证报错
export class AuthenticationError extends ApolloError { constructor(message: string) { super(message, 'UNAUTHENTICATED'); Object.defineProperty(this, 'name', { value: 'AuthenticationError' }); } }
接受的参数是 message,能够外部传入,可是code参数是指定的 UNAUTHENTICATED
应用场景:用户身份有问题
if (!authorization) throw new AuthenticationError('You must be logged in')
报错的code为 UNAUTHENTICATED
前端输出一下此时的error
用户输入信息报错
export class UserInputError extends ApolloError { constructor(message: string, properties?: Record<string, any>) { super(message, 'BAD_USER_INPUT', properties); Object.defineProperty(this, 'name', { value: 'UserInputError' }); } }
通常在检查form表单字段的时候,若是不知足条件,能够上报此error
接受两个参数,message 和 properties
报错的code为 BAD_USER_INPUT
前端输出一下此时的error
参数检验报错
export class ValidationError extends ApolloError { constructor(message: string) { super(message, 'GRAPHQL_VALIDATION_FAILED'); Object.defineProperty(this, 'name', { value: 'ValidationError' }); } }
报错的code为 GRAPHQL_VALIDATION_FAILED
前端输出一下此时的error