Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No nice way to handle 202 Accepted #228

Closed
voronaam opened this issue Apr 10, 2024 · 2 comments
Closed

No nice way to handle 202 Accepted #228

voronaam opened this issue Apr 10, 2024 · 2 comments
Labels

Comments

@voronaam
Copy link

We were pretty happy with a nice

api.post(content)
  .json()
  .then((responseBody) => {...})

Until the backend added a feature to process large requests in the background. In which case the API return HTTP 202 Accepted and no body.

I tried to catch it with .error(202, (res) => {...}) but since 202 is not a error response, it did not work.

In the end I had to resort to the raw response handling as in:

api.post(content)
  .res((raw_response) => {
    if (raw_response.status === 202) {
      notifyUser('background processing');
      return;
    }
    raw_response.json().then((responseBody) => {...})
  });

The actual code is a bit more ugly because of extra .catch(...) everywhere.

Is there a more wretch-like way to handle the 202 response status?

@elbywan
Copy link
Owner

elbywan commented May 11, 2024

Hey @voronaam, sorry for the late answer.

Is there a more wretch-like way to handle the 202 response status?

One way of doing this would be to add a tiny middleware which throws a custom error on 202s and catch it:

class NoContentError extends Error {
  name = 'NoContentError';
  message = '202 No Content';
}

const api = wretch(`https://httpstat.us`)
  .middlewares([next => async (url, opts) => {
    const res = await next(url, opts);
    if (res.status === 202) {
      throw new NoContentError()
    }
    return res;
  }])
  .catcher("NoContentError", (error) => {
    console.log(error.message)
  })

api.url('/200')
  .post({ hello: "world" })
  .text((responseBody) => {
    console.log(responseBody)
  })

api.url('/202')
  .post({ hello: "world" })
  .text((responseBody) => {
    console.log(responseBody)
  })

@voronaam
Copy link
Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants