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

async attempt #5837

Open
eglove opened this issue Mar 31, 2024 · 0 comments
Open

async attempt #5837

eglove opened this issue Mar 31, 2024 · 0 comments

Comments

@eglove
Copy link

eglove commented Mar 31, 2024

attempt currently does not catch errors that come from promises. Instead, it will throw. I tried to send a PR for this, but the contribution docs look old (test files are named with .spec, not .test). I don't see how you're running tests.

For example, this will throw:

const request = new Request('http://example.com', {
  body: '',
  method: 'POST',
});

// STILL THROWS
const body = await attempt(async () => {
  return request.json();
});

However, if we have an async version that awaits the promise before, we can get the same results:

import attempt from 'lodash/attempt.js';
import isError from 'lodash/isError.js';

export async function attemptAsync(...parameters: Parameters<typeof attempt>) {
  try {
    return await attempt(...parameters);
  } catch (error: unknown) {
    return isError(error) ? error : new Error(error);
  }
}

Now we get the expected results:

const request = new Request('http://example.com', {
  body: '',
  method: 'POST',
});

const body = await attemptAsync(async () => {
  return request.json();
});
  
expect(isError(body)).toBe(true);
expect(body).toBeInstanceOf(SyntaxError);

if (body instanceof SyntaxError) {
  expect(body.message).toBe('Unexpected end of JSON input');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant