Skip to content

Instantly share code, notes, and snippets.

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

  • Save chnn/3bd49363b101f15588fc2d9d2b87ef8a to your computer and use it in GitHub Desktop.

Select an option

Save chnn/3bd49363b101f15588fc2d9d2b87ef8a 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: Fetch

  • Error path is typed
  • Unfamiliar compared to our current style
  • Allows streaming a request body if we want to (for queries)
let cells: Cell[] // = ...

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

  if (resp.status === 200) {
    console.log("updated cells", body) // body of type `Cell[]`
  } else if (resp.status === 404) {
    notify(body.message)
  } else {
    reportErrorToHoneyBadger(body)
  }
} 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