Skip to content

Instantly share code, notes, and snippets.

@chnn
Created July 18, 2019 19:22
Show Gist options
  • Select an option

  • Save chnn/818077eb8ea4c260f78089b46ead429e to your computer and use it in GitHub Desktop.

Select an option

Save chnn/818077eb8ea4c260f78089b46ead429e to your computer and use it in GitHub Desktop.

Option 1: Axios

  • Our current style
  • Easier for the success path
  • Error path is untyped
let cells: Cell[] // = ...

try {
  const resp = await updateDashboardCells({dashboardID: 123, body: cells})

  console.log("updated cells", resp.data) // resp.data of type `Cell[]`
} catch (error) {
  if (error.response) {
    // ⚠️ `error.response` is of type `any`, and it is impossible to specify it
    // otherwise. But this is where we would handle non-2xx responses that have
    // a schema in the OpenAPI spec
    if (error.response.status === 404) {
      notify(error.response.data)
    } else {
      reportErrorToHoneyBadger(error.response.data)
    }
  } else if (axios.isCancel(error) {
    return // request was canceled
  } else {
    reportErrorToHoneyBadger(error)
  }
}

Option 2: Axios or fetch with custom wrapper

  • Error path is typed
  • Unfamiliar compared to our current style
let cells: Cell[] // = ...

try {
  const resp = await updateDashboardCells({dashboardID: 123, body: cells})

  if (resp.status === 200) {
    console.log("updated cells", resp.data) // resp.data of type `Cell[]`
  } else if (resp.status === 404) {
    notify(resp.data.message) // resp.data.message of type `string`
  } else {
    reportErrorToHoneyBadger(resp.data)  // resp.data of type `DefaultError`
  }
} catch (error) {
  if (error.name === 'AbortError') {
    return // request was cancelled
  }

  reportErrorToHoneyBadger(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment