Non error promise rejection captured with value timeout

Exception: UnhandledRejection: Non-Error promise rejection captured with value: Timeout #5833 Comments Is there an existing issue for this? I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues I have reviewed the documentation https://docs.sentry.io/ I am using the latest SDK release https://github.com/getsentry/sentry-javascript/releases How do you use Sentry? Sentry Saas (sentry.io) Which package are you using? SDK Version […]

Содержание

  1. Exception: UnhandledRejection: Non-Error promise rejection captured with value: Timeout #5833
  2. Comments
  3. Is there an existing issue for this?
  4. How do you use Sentry?
  5. Which package are you using?
  6. SDK Version
  7. Framework Version
  8. Link to Sentry event
  9. Steps to Reproduce
  10. Expected Result
  11. Actual Result
  12. Troubleshooting
  13. Console flooded with «Non-Error promise rejection captured with value: undefined» #3095
  14. Comments
  15. Version
  16. Reproduction link
  17. Steps to reproduce
  18. What is expected?
  19. What is actually happening?
  20. «Non-Error promise rejection captured with value:» #3440
  21. Comments
  22. DOMExceptions captured by onunhandledrejection as «Non-Error promise rejection captured with keys: [object has no keys]» #2244
  23. Comments
  24. Package + Version
  25. Version:
  26. Description

Exception: UnhandledRejection: Non-Error promise rejection captured with value: Timeout #5833

Is there an existing issue for this?

  • I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues
  • I have reviewed the documentation https://docs.sentry.io/
  • I am using the latest SDK release https://github.com/getsentry/sentry-javascript/releases

How do you use Sentry?

Sentry Saas (sentry.io)

Which package are you using?

SDK Version

Framework Version

Link to Sentry event

Steps to Reproduce

In my app, I’ve received thousands (almost 5K for a month) of

UnhandledRejection: Non-Error promise rejection captured with value: Timeout

.
I’ve searched through our code and all compiled third-party code, looking for Timeout. This string isn’t thrown or passed to reject() anywhere. It’s pretty difficult to narrow down the root of the problem as there’s virtually no information about the script that is causing it. I suggest that this is coming from a third-part lib that loaded at runtime. Console points to this function in recaptch_en_gb.js:
«function» === typeof window[D] ? Promise.resolve().then(window[D]) : «function» === typeof D ? Promise.resolve().then(D) : D && console.log(«reCAPTCHA couldn’t find user-provided function: » + D)
It looks like the same issue as 2514 that has been closed.

Expected Result

I’m suggesting to add some custom code to @sentry/gatsby (if there isn’t already) for handling this special case with non-Error types properly.

Actual Result

The text was updated successfully, but these errors were encountered:

Источник

Troubleshooting

If you need help solving issues with your Sentry JavaScript SDK integration, you can read the edge cases documented below. If you need additional help, you can ask on GitHub

. Customers on a paid plan may also contact support.

Updating to a New Sentry SDK Version

If you update your Sentry SDK to a new major version, you might encounter breaking changes that need some adaption on your end. Check out our migration guide

to learn everything you need to know to get up and running again with the latest Sentry features.

Debugging Additional Data

You can view the JSON payload of an event to see how Sentry stores additional data in the event. The shape of the data may not exactly match the description.

Max JSON Payload Size

maxValueLength has a default value of 250, but you can adjust this value according to your needs if your messages are longer. Please note that not every single value is affected by this option.

CORS Attributes and Headers

To gain visibility into a JavaScript exception thrown from scripts originating from different origins, do two things:

  1. Add a crossorigin=”anonymous” script attribute

The script attribute tells the browser to fetch the target file “anonymously.” Potentially user-identifying information like cookies or HTTP credentials won’t be transmitted by the browser to the server when requesting this file.

  1. Add a Cross-Origin HTTP header

Cross-Origin Resource Sharing (CORS) is a set of APIs (mostly HTTP headers) that dictate how files ought to be downloaded and served across origins.

By setting Access-Control-Allow-Origin: * , the server is indicating to browsers that any origin can fetch this file. Alternatively, you can restrict it to a known origin you control:

Most community CDNs properly set an Access-Control-Allow-Origin header.

Unexpected OPTIONS request

If your application started to misbehave because of performing additional OPTIONS requests, it is most likely an issue with unwanted sentry-trace request headers, which can happen when you are using too generic a configuration for our Tracing Integration in the Browser SDK.

To fix this, change the tracePropagationTargets option during SDK initialization. For more details, see Automatic Instrumentation in our Performance Monitoring documentation.

instrument.js Line Numbers for Console Log statements

If instrument.js displays in your console while debugging, add Sentry to your Framework Ignore List

by adding this pattern: /@sentry/

Chrome then ignores the SDK stack frames when debugging.

Dealing with Ad-Blockers

When you are using our CDN, ad-blocking or script-blocking extensions may prevent our SDK from being fetched and initialized properly. Because of this, any call to the SDKs API will fail and may cause your application to behave unexpectedly.

Additionally, even when the SDK is downloaded and initialized correctly, Sentry endpoints that need to receive captured data may be blocked as well. This prevents any error reports, sessions health, or performance data from being delivered, making it effectively unavailable in sentry.io

You can work around the first issue in multiple ways explained above. However, the endpoint blockage can be only resolved using the tunnel.

Using the tunnel Option

A tunnel is an HTTP endpoint that acts as a proxy between Sentry and your application. Because you control this server, there is no risk of any requests sent to it being blocked. When the endpoint lives under the same origin (although it does not have to in order for the tunnel to work), the browser will not treat any requests to the endpoint as a third-party request. As a result, these requests will have different security measures applied which, by default, don’t trigger ad-blockers. A quick summary of the flow can be found below.

Starting with version 6.7.0 of the JavaScript SDK, you can use the tunnel option to tell the SDK to deliver events to the configured URL, instead of using the DSN. This allows the SDK to remove sentry_key from the query parameters, which is one of the main reasons ad-blockers prevent sending events in the first place. This option also stops the SDK from sending preflight requests, which was one of the requirements that necessitated sending the sentry_key in the query parameters.

Источник

Console flooded with «Non-Error promise rejection captured with value: undefined» #3095

Version

Reproduction link

Steps to reproduce

I’m calling context.redirect(«/») in Nuxt.js middleware. I’ve found the exact lines in vue-router source code where it rejects with undefined .

What is expected?

Promise rejections contain error object or do not reject.

What is actually happening?

Console is flooded with «Non-Error promise rejection captured with value: undefined». We receive huge amount of Sentry issues automatically caught as UnhandledRejection

The History.confirmTransition method calls the function abort() (stack trace shows this exact line

The onAbort then calls reject(err) (as Promise rejection), but the err is undefined (because abort() ).

I assume, that the rejection should never happen.

To my very limited knowledge this line:

should be replaced with this:

The text was updated successfully, but these errors were encountered:

Could be as well Nuxt.js bug. They promisify the next router calls and could be that the promisificaiton went wrong.

Have same problem

In / redirect that throw error
Some bad fix

This is related to the promise api when no callbacks are passed to push/replace. You can find about it in the docs and an explanation behind the change at #2881 (comment)

@Kolobok12309 you should be able to find the answer in that comment

@koresar in your case, it’s a bit different because you are using a redirect, which internally is probably calling next inside a beforeEach hook, causing a redirection, aborting the previous call of router.push / router.replace and causing that specific call to return a rejected promise. If that’s not what you did, then I will need a boiled down repro (it can use Nuxt) to check it, ping me once you have one.

The Promise API for navigation will go through an RFC for the next version of Vue Router, especially for what should and should not reject the promise

Источник

«Non-Error promise rejection captured with value:» #3440

I didn’t want to create a bug as I don’t believe there is a bug here considering this error has been talked about a few times here. TL:DR — We are receiving a copious amount i these errors with no values provided. I can’t see anything that sticks out in our code for why this is happening, but I don’t want to dismiss this as an external factor. Some information about our Sentry Setup:

Was curious if anyone has any advice/thoughts on how to to begin debugging this further? Thanks in advance for your time!

The text was updated successfully, but these errors were encountered:

Unfortunately, there’s nothing we can extract from promise rejections that were thrown with an empty string. Even trying to «fake» an error doesn’t provide a valid stack trace, as global error handlers are not keeping track of the callers.

This event is produced in one of three ways:

In order for us to extract the stack trace, rejections/throws inside async functions have to be done through an Error instance.

This started happening to us on April 16th, on a day where we didn’t change any code at all. Since them we’ve had 98k of these errors. We’ve added some code to filter this out in our js as we can’t figure out a way to silence these at all. I’m guessing it’s related to some password manager like lastpass as it only happens on our login page, with chrome, on windows 10. We’ve added code like:

If there’s a better way to deal with this, I’d love to know about it. On one hand, I can see how you don’t want to editorialize here and prevent these errors, but when there’s no info at all there’s nothing actionable and we can’t do anything about it other than be annoyed.

Thanks for the insight here! Really helpful. We are having the same affected browser and device, but really can’t tell where this is coming from.

@kamilogorek said it great where it is just returning an empty error object so not much Sentry can do here. Would be cool to know the origin of the error maybe? Not sure how this works with extensions.

Either way appreciate the insight!

Adding an update for anyone else, this problem has evolved to be a «Non-Error promise rejection captured with value: Object Not Found Matching Id:5» error, so we had to update our hack to deal with that. We decided to just put the hack on the login page, as it appears this is from some password manager browser extension.

We are also getting this error, both empty and now with the «Object Not Found Matching Id:» message. I want to point out that while we do not have a login page we do have forms all over the site and there’s two characteristics that stick out:

  • Some of the URLs do not exist. Part of the path would be valid but the last part is just gibberish. ie: /blog/fashion/AWBM2HW instead of a real post’s title. The random part repeats itself on different clients, it’s not like every error has a different slug. This 404 page has no form in it.
  • Most other URLs are links sent through email to our clients. Too many of them for it to be a random coincidence. In fact the gibberish links from before are related to links we’ve sent through email.

It may be a completely different issue from yours @wynnw but who knows.

This is most likely happening due to the safe links being scanned by Outlook

If you have an Office 365 subscription and your emails contain links to your site and these links use Safe Links feature then it is bound to happen

We were able to reproduce this and get the error in Sentry

In the next version — 6.9.0 (releasing as we speak), Dedupe integration is turned on by default, which should lower the impact of this issue tremendously.

Is there any way to disable sending those events to sentry? We are on 6.13.3 (Next.js package) and are seeing a very high number of such errors.

or through beforeSend callback.

It’s been a while, but this has come up again so just going to chime in here:

All of the above hacks work, but are broader than they need to be, and therefore risk filtering out unrelated events.

As Kamil said above, Non-Error promise rejection captured. is what we send when a promise rejects with something other than an instance of the Error class/an instance of an Error subclass. Most often we catch these once they hit the global error handler, but this can also happen if captureException is called explicitly on the rejected object ( try < await asyncThing() >catch (err) < Sentry.captureException(err) >, where err is null/undefined/a string/some other random object).

Since this can happen in any number of different circumstances, if you want to filter the events mentioned above (empty rejections and rejections with the Object Not Found Matching Id message), better to actually filter specifically on those. (For that, you can use either the beforeSend code from @wynnw or the ignoreErrors code from Kamil. In either case, you’d want to use a regex rather than a substring match for the empty rejection so you can make sure it’s empty, and a check on the actual error message for the Object Not Found.. rejection.)

As for the Dedupe integration Kamil mentioned, it will only help in cases where a) there is an exact match on message (so no varying URLs) and b) when no other error happens in the meantime (IOW, if you have error A followed by error A, the second one will be dropped, but if you have error A, error B, and then error A again, they’ll all go through). This is probably why @michaelschufi was still seeing lots of these errors even after we turned Dedupe on by default. Filtering on the actual errors should make this a moot point, though.

Ultimately, the ideal solution would be to work with the Outlook folks to get them to not throw the error in the first place.

Источник

DOMExceptions captured by onunhandledrejection as «Non-Error promise rejection captured with keys: [object has no keys]» #2244

  • Review the documentation: https://docs.sentry.io/
  • Search for existing issues: https://github.com/getsentry/sentry-javascript/issues
  • Use the latest release: https://github.com/getsentry/sentry-javascript/releases
  • Provide a link to the affected event from your Sentry account

Package + Version

  • @sentry/browser
  • @sentry/node
  • raven-js
  • raven-node (raven for node)
  • other:

Version:

Description

Possibly related to #2210 though I wasn’t sure if that was just focused on custom error events

I’m seeing a lot of UnhandledRejection events in our dashboard with the following message: Non-Error promise rejection captured with keys: [object has no keys] . After digging in a bit, it looks like it’s mostly DOMExceptions , which don’t have a .stack property so they’re logged like non-Errors.

It does log the details in the serialized property, for example:

Looks like DOMExceptions were handled in raven-js in this pull request: #1310 Could they be handled similarly gracefully in onunhandledrejection? It seems like various browser things like fetch and even media methods like play() (like the above serialized error) throw DOMException errors, and having them all roll up into that confusing error message makes it tougher to debug.

The text was updated successfully, but these errors were encountered:

Источник

I am having issues with getting source maps to work. I am experiencing issues with «Invalid location in sourcemap (see Troubleshooting for JavaScript)»

const path = require("path");
const slsw = require("serverless-webpack");
const CopyPlugin = require("copy-webpack-plugin");
const SentryPlugin = require("@sentry/webpack-plugin");
const webpack = require("webpack");

module.exports = {
  plugins: [
    new webpack.SourceMapDevToolPlugin({
      noSources: false,
      filename: "[name].js.map",
    }),
    new SentryPlugin({
      release: process.env.SERVICE_VERSION,
      org: process.env.SENTRY_ORGANIZATION,
      project: process.env.SENTRY_PROJECT,
      authToken: process.env.SENTRY_AUTH_TOKEN,
      include: ".webpack",
      ignore: ["node_modules", "webpack.config.js"],
      setCommits: {
        auto: true,
      },
      deploy: {
        env: process.env.SENTRY_ENV || "ENV_NAME_NOT_PROVIDED",
      },
      validate: true,
      sourceMapReference: true,
    }),
  ],
  entry: slsw.lib.entries,
  mode: "none",
  target: "node14",
  externals: ["aws-sdk"],
  node: {
    __dirname: true,
  },
  resolve: {
    extensions: [".js", ".json", ".ts", ".tsx"],
  },
  optimization: {
    minimize: false,
  },
  output: {
    libraryTarget: "commonjs",
    path: path.join(__dirname, ".webpack"),
    filename: "[name].js",
  },
  ignoreWarnings: [
    {
      module: /node_modules/typeorm/,
      message: /Can't resolve/,
    },
    {
      module: /node_modules/,
      message: /Critical dependency: the request of a dependency is an expression/,
    },
  ],
  module: {
    rules: [
      {
        test: /.ts(x?)$/,
        exclude: [/plop-templates/, /node_modules/],
        use: [
          {
            loader: "ts-loader",
            options: {
              transpileOnly: process.env.NODE_ENV !== "dev",
            },
          },
        ],
      },
      {
        test: /.js$/,
        exclude: [/node_modules/, /plop-templates/],
        use: [
          {
            loader: "babel-loader",
          },
        ],
      },
    ],
  },
};
{
"function": "<anonymous>",
"module": "functions.test-sentry-tag-lambda:handler",
"filename": "/var/task/test-sentry-tag-lambda/handler.js.map",
"abs_path": "/var/task/test-sentry-tag-lambda/handler.js.map",
"lineno": 38803,
"colno": 18,
"context_line": "",
"in_app": true
},

Время прочтения
5 мин

Просмотры 17K

Доброго времени суток, друзья!

Хотел бы я знать об этих ошибках, когда изучал JavaScript и промисы.

Всякий раз, когда ко мне обращается какой-нибудь разработчик и жалуется на то, что его код не работает или медленно выполняется, я прежде всего обращаю внимание на эти ошибки. Когда я начал программировать 4 года назад, я не знал о них и привык их игнорировать. Однако после назначения в проект, который обрабатывает около миллиона запросов в течение нескольких минут, у меня не было другого выбора, кроме как оптимизировать свой код (поскольку мы достигли уровня, когда дальнейшее вертикальное масштабирование стало невозможным).

Поэтому в данной статье я бы хотел поговорить о самых распространенных ошибках при работе с промисами в JS, на которые многие не обращают внимания.

Ошибка № 1. Использование блока try/catch внутри промиса

Использовать блок try/catch внутри промиса нецелесообразно, поскольку если Ваш код выдаст ошибку (внутри промиса), она будет перехвачена обработчиком ошибок самого промиса.

Речь идет вот о чем:

new Promise((resolve, reject) => {
  try {
    const data = someFunction()
    // ваш код
    resolve()
  } catch(e) {
    reject(e)
  }
})
  .then(data => console.log(data))
  .catch(error => console.log(error))

Вместо этого позвольте коду обработать ошибку вне промиса:

new Promise((resolve, reject) => {
  const data = someFunction()
  // ваш код
  resolve(data)
})
  .then(data => console.log(data))
  .catch(error => console.log(error))

Это будет работать всегда, за исключением случая, описанного ниже.

Ошибка № 2. Использование асинхронной функции внутри промиса

При использовании асинхронной функции внутри промиса возникают некоторые неприятные побочные эффекты.

Допустим, Вы решили выполнить некоторую асинхронную задачу, добавили в промис ключевое слово «async», и Ваш код выдает ошибку. Однако теперь Вы не можете обработать эту ошибку ни с помощью .catch(), ни с помощью await:

// этот код не сможет перехватить ошибку
new Promise(async() => {
  throw new Error('message')
}).catch(e => console.log(e.message))

// этот код также не сможет перехватить ошибку
(async() => {
  try {
    await new Promise(async() => {
      throw new Error('message')
    })
  } catch(e) {
    console.log(e.message)
  }
})();

Каждый раз, когда я встречаю асинхронную функцию внутри промиса, я пытаюсь их разделить. И у меня это получается в 9 из 10 случаев. Тем не менее, это не всегда возможно. В таком случае у Вас нет другого выбора, кроме как использовать блок try/catch внутри промиса (да, это противоречит первой ошибке, но это единственный выход):

new Promise(async(resolve, reject) => {
  try {
    throw new Error('message')
  } catch(error) {
    reject(error)
  }
}).catch(e => console.log(e.message))

// или используя async/await
(async() => {
  try {
    await new Promise(async(resolve, reject) => {
      try {
        throw new Error('message')
      } catch(error) {
        reject(error)
      }
    })
  } catch(e) {
    console.log(e.message)
  }
})();

Ошибка № 3. Забывать про .catch()

Эта одна из тех ошибок, о существовании которой даже не подозреваешь, пока не начнется тестирование. Либо, если Вы какой-нибудь атеист, который не верит в тесты, Ваш код обязательно рухнет в продакшне. Потому что продакшн строго следует закону Мерфи, который гласит: «Anything that can go wrong will go wrong» (можно перевести так: «Если что-то может пойти не так, это обязательно произойдет»; аналогией в русском языке является «закон подлости» — прим. пер.).

Для того, чтобы сделать код элегантнее, можно обернуть промис в try/catch вместо использования .then().catch().

Ошибка № 4. Не использовать Promise.all()

Promise.all() — твой друг.

Если Вы профессиональный разработчик, Вы наверняка понимаете, что я хочу сказать. Если у Вас есть несколько не зависящих друг от друга промисов, Вы можете выполнить их одновременно. По умолчанию, промисы выполняются параллельно, однако если Вам необходимо выполнить их последовательно (с помощью await), это займет много времени. Promise.all() позволяет сильно сократить время ожидания:

const {promisify} = require('util')
const sleep = promisify(setTimeout)

async function f1() {
  await sleep(1000)
}
async function f2() {
  await sleep(2000)
}
async function f3() {
  await sleep(3000)
}

// выполняем последовательно
(async() => {
  console.time('sequential')
  await f1()
  await f2()
  await f3()
  console.timeEnd('sequential') // около 6 секунд
})();

Теперь с Promise.all():

(async() => {
  console.time('concurrent')
  await Promise.all([f1(), f2(), f3()])
  console.timeEnd('concurrent') // около 3 секунд
})();

Ошибка № 5. Неправильное использование Promise.race()

Promise.race() не всегда делает Ваш код быстрее.

Это может показаться странным, но это действительно так. Я не утверждаю, что Promise.race() — бесполезный метод, но Вы должны четко понимать, зачем его используете.

Вы, например, можете использовать Promise.race() для запуска кода после разрешения любого из промисов. Но это не означает, что выполнение кода, следующего за промисами, начнется сразу же после разрешения одного из них. Promise.race() будет ждать разрешения всех промисов и только после этого освободит поток:

const {promisify} = require('util')
const sleep = promisify(setTimeout)

async function f1() {
  await sleep(1000)
}
async function f2() {
  await sleep(2000)
}
async function f3() {
  await sleep(3000)
}

(async() => {
  console.time('race')
  await Promise.race([f1(), f2(), f3()])
})();

process.on('exit', () => {
 console.timeEnd('race') // около 3 секунд, код не стал быстрее!
})

Ошибка № 6. Злоупотребление промисами

Промисы делают код медленнее, так что не злоупотребляйте ими.

Часто приходится видеть разработчиков, использующих длинную цепочку .then(), чтобы их код выглядел лучше. Вы и глазом не успеете моргнуть, как эта цепочка станет слишком длинной. Для того, чтобы наглядно убедиться в негативных последствиях такой ситуации, необходимо (далее я немного отступлю от оригинального текста для того, чтобы описать процесс подробнее, нежели в статье — прим. пер.):

1) создать файл script.js следующего содержания (с лишними промисами):

new Promise((resolve) => {
  // некий код, возвращающий данные пользователя
  const user = {
    name: 'John Doe',
    age: 50,
  }
  resolve(user)
}).then(userObj => {
    const {age} = userObj
    return age
}).then(age => {
  if(age > 25) {
    return true
  }
throw new Error('Age is less than 25')
}).then(() => {
  console.log('Age is greater than 25')
}).catch(e => {
  console.log(e.message)
})

2) открыть командную строку (для пользователей Windows: чтобы открыть командную строку в папке с нужным файлом, зажимаем Shift, кликаем правой кнопкой мыши, выбираем «Открыть окно команд»), запустить script.js с помощью следующей команды (должен быть установлен Node.js):

node --trace-events-enabled script.js

3) Node.js создает файл журнала (в моем случае node_trace.1.txt) в папке со скриптом;

4) открываем Chrome (потому что это работает только в нем), вводим в адресной строке «chrome://tracing»;

5) нажимаем Load, загружаем файл журнала, созданного Node.js;

6) открываем вкладку Promise.

Видим примерно следующее:

Зеленые блоки — промисы, выполнение каждого из которых занимает несколько миллисекунд. Следовательно, чем больше будет промисов, тем дольше они будут выполняться.

Перепишем script.js:

new Promise((resolve, reject) => {
  const user = {
    name: 'John Doe',
    age: 50,
  }
  if(user.age > 25) {
    resolve()
  } else {
    reject('Age is less than 25')
  }
}).then(() => {
  console.log('Age is greater than 25')
}).catch(e => {
  console.log(e.message)
})

Повторим «трассировку».

Видим следующее:

Зеленых блоков (промисов) стало меньше, а значит время выполнения кода сократилось.

Таким образом, использовать несколько промисов следует только в том случае, если Вам необходимо выполнить некоторый асинхронный код.

Благодарю за внимание.

Skip to content



Open


Issue created Jun 24, 2021 by Patrick Vale@yaffolMaintainer7 of 15 checklist items completed7/15 checklist items

Add Unhandled rejections to ignoreErrors configuration of Sentry Javascript SDK

Background

We are getting occasional but regular spikes or errors (approx 250 in a day, occurring one day every few weeks) like

UnhandledRejection: Non-Error promise rejection captured with value: Object Not Found Matching Id:1

This is reported by Sentry on their forum as:

These types of events are caused when a rejection is raised with a non-error object, from which we cannot extract much information.

These can be filtered by using the ignoreErrors option.

Sentry.init({
    dsn:__MY_DSN__,
      ignoreErrors:[
       "Non-Error exception captured",
       "Non-Error promise rejection captured"
      ]
    })

And also that ‘we are going to make the Dedupe integration default for browser again which solves this problem.’

It’s also been reported that

All of the errors I have checked are coming from Microsoft ip addresses and to urls that are only available from emails our system has sent, so they are probably just Outlook Safe Link scanning for malicious websites.

Which tallies with our investigation — all of the IP addresses associated with this error belong to the MICROSOFT-CORP-MSN-AS-BLOCK autonomous system.

We should add these error patterns to the ignoreErrors key of the Sentry Javascript SDK configuration, and update the Sentry Javascript SDK version within the Frontend, then update CS Login Screen and webDeposit to use the new Frontend release.

Observed behavior

We are seeings spikes of errors which are not relevant and use up our Sentry quota.

Expected behavior

We should filter out these errors so they don’t use our quota.

How urgent

It’s using quota but not enormously. It could spike more and become more urgent. Since setting the 250/hour sentry events rate limit it’s got a usage cap in place.

Definition of ready

  • Product owner: n/a
  • Tech lead: @yaffol
  • Service:: or C:: label applied
  • Definition of done updated
  • Acceptance testing plan: Confirm in production sentry
  • Weight applied

Definition of done

  • Code reviewed
  • Consider any impacts to current or future architecture/infrastructure, and update specifications and documentation as needed
  • Acceptance criteria met

    • These ‘UnhandledRejection Errors are filtered
    • Sentry Javascript SDK verion updated
    • Frontend release version updated in CS and webDeposit (should this be separate tickets?)
    • Put usage capping on these errors, like we did for CS errors
  • Acceptance testing passed
  • Deployed to production

Notes

Edited Jul 15, 2021 by Patrick Polischuk

Package + Version

  • [x] @sentry/browser
  • [ ] @sentry/node
  • [ ] raven-js
  • [ ] raven-node (raven for node)
  • [ ] other:

Version:

5.10.2

Description

My project often catch an error like Event Non-Error promise rejection captured with keys: currentTarget, isTrusted, target, type,without any useful information. And an additional data is

__serialized__ = {
    currentTarget: [object Null], 
    isTrusted: [Circular ~], 
    target: head > script[type="text/javascript"], 
    type: error
}

looks like an Event instance. With the limited information,I don’t know where this bug is triggered,has anyone encountered the same problem?

Asked Oct 23 ’21 04:10

avatar susan-github


susan-github

9 Answer:

It seems that this issue is caused by something roughly like this:

new Promise((resolve, reject) => {
  const script = document.createElement('script');
  script.src = src;
  script.onload = resolve;
  script.onerror = reject;
  document.body.appendChild(script);
});

The onerror hook will actually receive an Event object, instead of an Error instance, which is causing these issues that are mentioned above. This can be avoided by wrapping the Event with an Error as suggested by https://developer.mozilla.org/de/docs/Web/API/HTMLScriptElement:

new Promise((resolve, reject) => {
  const script = document.createElement('script');
  script.src = src;
  script.onload = resolve;
  script.onerror = event => {
    reject(new Error(`Failed to load ${event.target.src}`));
  };
  document.body.appendChild(script);
});



1

Answered Oct 04 ’20 at 23:28

avatar  of Turbo87


Turbo87

@sheelah there’s not much we can improve here, to be honest. JS doesn’t give us more information that we already provide. Whenever an instance of a promise object is rejected, it triggers onunhandledrejection event (same goes for onerror in the OP description).

https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

However, there’s nothing that would stop anyone from passing any random stuff in there.
Thus code like this Promise.reject("whatever") or Promise.reject(jQueryBecauseWhyNot) is totally valid JS code.

Whenever we encounter something that’s not a primitive value, an object that contains the stack trace (eg. Error) or internal DOM exception, we have to fall back to simple object serialization and try to extract whatever information we can out of it. You can see eventbuilder.ts file for a list of possible paths this «any random value» passed to the event handler can take – https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/eventbuilder.ts#L17-L80

Unfortunately, I’m not sure if we can make it any more generic to handle more types of input.
If anyone has any feedback regarding that process, I’m totally open to suggestions.

(answered here instead of to your email, to keep the conversation public for everyone else)



1

Answered Jun 17 ’20 at 12:58

avatar  of kamilogorek


kamilogorek

In my case it was Next.js’ 9.5.2 prefetching mechanism causing it on Firefox, just in case somebody has a similar case. (maybe here? https://github.com/getsentry/sentry-javascript/issues/2546#issuecomment-697771381) This is the issue: https://github.com/vercel/next.js/pull/16757 and can be solved by upgrading to 9.5.3 or Canary.

The error is much more verbose in the browser, though:

Uncaught (in promise) 
error
bubbles: false
...
...
as: "fetch"
assignedSlot: null
attributes: NamedNodeMap(3
0: href="/_next/data/wmQYPCwvbuBulJfEwTMRf/smartwatches/fitbit-ionic.json"
1: rel="prefetch"
2: as="fetch"
as: as="fetch"
href: href="/_next/data/wmQYPCwvbuBulJfEwTMRf/smartwatches/fitbit-ionic.json"
length: 3
rel: rel="prefetch"
...
...
​
isTrusted: true
originalTarget: <link href="/_next/data/wmQYPCwvbuBu…tches/fitbit-ionic.json" rel="prefetch" as="fetch">
returnValue: true
srcElement: <link href="/_next/data/wmQYPCwvbuBu…tches/fitbit-ionic.json" rel="prefetch" as="fetch">​
target: <link href="/_next/data/wmQYPCwvbuBu…tches/fitbit-ionic.json" rel="prefetch" as="fetch">
timeStmp: 25366
type: "error"
...

How can we get Sentry to capture this data?



1

Answered Oct 05 ’20 at 03:23

avatar  of nickluger


nickluger

From my observations:

  • Only happens in various recent versions of Safari on mobile or desktop;
  • I have a few libraries installed in my web app such as ZXing and browser-image-compression, but no third-party tracking scripts;
  • It seems to occur at the exact same time as an API call fails with a Network Error (code 0).
  • In my case, it is more specifically a ProgressEvent, not just an event — which seems to be a part of HTTP request library (I am using axios).
ADDITIONAL DATA

__serialized__ | {
    currentTarget: [object Null],
    isTrusted: [Circular ~],
    target: [object FileReader],
    type: error}
-- | --



1

Answered Jun 18 ’20 at 03:07

avatar  of anton-bot


anton-bot

We’ve also started seeing these in the last couple of weeks. I just started looking into it so I don’t have any more details on what’s causing it.



1

Answered May 29 ’20 at 13:21

avatar  of qtiki


qtiki

Can someone provide any link to this type of event captured in Sentry? It looks like a script loading error (notice the target that this event has been triggered on)



1

Answered Jun 10 ’20 at 10:24

avatar  of kamilogorek


kamilogorek

@kamilogorek can you please send me your company email? I can share examples of the events.



1

Answered Jun 12 ’20 at 07:24

avatar  of Santas


Santas

If you need more examples I can send some over as well @kamilogorek — just let me know.



1

Answered Jun 12 ’20 at 20:54

avatar  of sheelah


sheelah

Like this post? Please share to your friends:
  • Nokia software recovery tool ошибка 0x80070002
  • Nodemon app crashed waiting for file changes before starting как исправить
  • Node js setup wizard ended prematurely because of an error
  • Node js cannot get ошибка
  • No world with name deerisle ошибка