handleXhrErrorResponse.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import * as Sentry from '@sentry/react';
  2. import type RequestError from 'sentry/utils/requestError/requestError';
  3. export function handleXhrErrorResponse(message: string, err: RequestError): void {
  4. // Sudo errors are handled separately elsewhere
  5. // @ts-expect-error Property 'code' does not exist on type 'string'
  6. if (!err || err.responseJSON?.detail?.code === 'sudo-required') {
  7. return;
  8. }
  9. const {responseJSON, status, message: causeMessage} = err;
  10. Sentry.withScope(scope => {
  11. // Turn `GET /dogs/are/great 500` into just `GET /dogs/are/great`
  12. const endpoint = causeMessage?.replace(new RegExp(` ${status}$`), '');
  13. scope.setTags({
  14. responseStatus: status,
  15. endpoint,
  16. });
  17. // TODO: If we discover that undefind response bodies don't break anything,
  18. // we can revert to bailing when `responseJSON` is falsy and always calling `setExtras`
  19. if (err.name !== 'UndefinedResponseBodyError') {
  20. scope.setExtras({
  21. status,
  22. responseJSON,
  23. });
  24. }
  25. Sentry.captureException(
  26. // We need to typecheck here even though `err` is typed in the function
  27. // signature because TS doesn't type thrown or rejected errors
  28. err instanceof Error ? new Error(message, {cause: err}) : new Error(message)
  29. );
  30. });
  31. }