Skip to content

Best way to access http status code? #562

Answered by kamranayub
weyert asked this question in General
Discussion options

You must be logged in to vote

Another option is to throw a custom error you can attach metadata to, this is how we typically handle this pattern.

interface FetchItemOptions {
  method: string;
  body?: unknown;
}

class FetchError extends Error {
  constructor(public res: Response, message?: string) {
    super(message)
  }
}

const fetchItem = (path: string, options: FetchItemOptions) => {
  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  };

  return fetch(`${PUBLIC_API_URL}/${path}`, {
    method: options.method,
    headers,
    body: options.body ? JSON.stringify(options.body) : undefined,
  }).then(async (response) => {
    const data = await response.json();

    if (r…

Replies: 2 comments 7 replies

Comment options

You must be logged in to vote
3 replies
@weyert
Comment options

@E-Rosa
Comment options

@TkDodo
Comment options

Comment options

You must be logged in to vote
4 replies
@weyert
Comment options

@igor-q-bio
Comment options

@burrayto
Comment options

@Deivid182
Comment options

Answer selected by weyert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
8 participants