As The last ship sailed towards the distant horizon I sat there watching on a rock My mind slowly drifting away Forming into my... Dreamtale
How to use Sentry fix bugs with CloudFlare Workers
2018-09-04 / 2 min read

Sentry is cross-platform application monitoring, with a focus on error reporting. https://sentry.io

addEventListener('fetch', event => {
  if(event.request.url.indexOf('firebase-storage')>=0){
      event.respondWith(handle(event,'firebase-storage.XXXXX.com','firebasestorage.googleapis.com'))
  } else if(event.request.url.indexOf('firebase-db')>=0){
      event.respondWith(handle(event,'firebase-db.XXXXXX.com','XXXXXXXX.firebaseio.com'))
  }
})
  

async function handle(event,a,b) {
<!-- more -->

  let request = event.request
  let newUrl = request.url.replace(a,b);

  let response =await fetch(newUrl,request);
  if(response.status == "404"){
      console.log( "log to sentry  <---");
    event.waitUntil( promisifiedSentryLog({message:newUrl+"   --->   " + response.status}));
  }
  return response;
}

/**
 * Calls out to our Sentry account to create an exception event
 *
 * Note that for this to work properly with the event.waitUntil() call in the
 * exception block within requestWithTLSHeader, this function must return a promise
 *
 * @returns {Promise}
 */
function promisifiedSentryLog(ex) {
    //Change these constants to your own Sentry values if you want to use this script
    const sentryProjectId = 'XXXX'
    const sentryAPIKey = 'XXXXXX'
    const sentrySecretKey = 'XXXXX'
    //Manually configure our call to Sentry
    let b = {
        project: sentryProjectId,
        logger: "javascript",
        platform: "javascript",
        exception: {
            values: [
                { type: "Error", value: ((ex) && (ex.message)) ? ex.message : 'Unknown' }
            ]
        }
    }
    let sentryUrl = `https://sentry.io/api/${sentryProjectId}/store/?sentry_version=7&sentry_client=raven-js%2F3.24.2&sentry_key=${sentryAPIKey}&sentry_secret=${sentrySecretKey}`
    /**
     * Fire off a POST request to Sentry's API, which includes our project
     * and credentials information, plus arbitrary logging data
     *
     * In this case, we're passing along the exception message,
     * but you could use this pattern to log anything you want
     *
     * Keep in mind that fetch returns a promise,
     * which is what makes this function compatible with event.waitUntil
     */
    return fetch(sentryUrl, { body: JSON.stringify(b), method: 'POST' })
}