Apollo 中的異常處理

項目開發中,咱們須要經過具體的error信息來告知前端如何處理報錯邏輯,好比登陸過時,須要前端退出登陸,清除登陸token等html

最近在找一個關於error上報的問題,把看到的一些資料整理了一下前端

項目架構: 前端使用GATSBY框架,server由於配合的是 koa, 因此主要使用的是 apollo-server-koanode

GraphQLError

graphql 中的 GraphQLError 繼承自 node的Error類bash

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

ApolloError 繼承自Error 按照GraphQLError 的定義實現markdown

// 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來處理不一樣的邏輯app

switch (code) {
        case 'WYB':
          alert('無感')
          break;
        default:
          alert('無羈')
          break;
    }
複製代碼

stacktrace

堆棧跟蹤框架

在前端頁面咱們log出error信息,能夠看到此參數,這個就相似 error.stack 的堆棧跟蹤koa

每一行都以 "at " 開頭。 每一幀描述了一個代碼中致使錯誤生成的調用點oop

若是不想進行錯誤幀上報,能夠在applo-serve中關閉

new ApolloServer ({ debug: false })
複製代碼

formatError

格式化ERROR

若是須要批量處理error信息,能夠在此方法中操做。好比添加error日誌警告功能等

new ApolloServer ({ 
    formatError: err => {
      console.log('請進行錯誤日誌上報')
      return err
    }
})
複製代碼

這裏能夠改寫error,好比添加一些屬性,也能夠直接返回error

幾種常見的Error

apollo 有幫助咱們建立了幾種常見的Error對象,可在不一樣的業務場景中使用,他們全都是繼承自 ApolloError ,只不過是將 name 屬性從新命名

AuthenticationError

身份驗證報錯

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

UserInputError

用戶輸入信息報錯

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

ValidationError

參數檢驗報錯

export class ValidationError extends ApolloError {
  constructor(message: string) {
    super(message, 'GRAPHQL_VALIDATION_FAILED');

    Object.defineProperty(this, 'name', { value: 'ValidationError' });
  }
}
複製代碼

報錯的code爲 GRAPHQL_VALIDATION_FAILED

前端輸出一下此時的error

資料

相關文章
相關標籤/搜索