Browse Source

chore: better error log

patch-1
Amio 6 years ago
parent
commit
c1424618e5
  1. 58
      libs/live-fetcher.js

58
libs/live-fetcher.js

@ -3,13 +3,26 @@ const pool = require('./live-pool.js')
const raven = require('./raven.js') const raven = require('./raven.js')
module.exports = async (scope, fn, paramsPath) => { module.exports = async (scope, fn, paramsPath) => {
const fetchKey = `#${scope} ${paramsPath}` const fetchKey = `#${scope}/${paramsPath}`
if (pool.has(fetchKey)) return pool.get(fetchKey) if (pool.has(fetchKey)) return pool.get(fetchKey)
console.time(fetchKey) const fetchStart = new Date()
const fetcher = fn(...paramsPath.split('/')).then( const fetcher = fn(...paramsPath.split('/')).then(
result => typeof result === 'object' ? result : { failed: true }, result => {
err => { const timeSpan = String(new Date() - fetchStart).padStart(4, ' ')
console.log(`${timeSpan}ms ${fetchKey}`)
return typeof result === 'object' ? result : { failed: true }
},
err => errorHandler(scope, paramsPath, err)
).finally(() => {
pool.delete(fetchKey)
})
pool.set(fetchKey, fetcher)
return fetcher
}
const errorHandler = (scope, paramsPath, err) => {
let status = 'unknown' let status = 'unknown'
if (err.response && err.response.status === 404) { if (err.response && err.response.status === 404) {
@ -18,33 +31,36 @@ module.exports = async (scope, fn, paramsPath) => {
status = 'timeout' status = 'timeout'
} }
errorLogger(fetchKey, err, status) errorLogger(`/${scope}/${paramsPath}`, err, status)
return { status, failed: true } return { status, failed: true }
}).finally(() => {
console.timeEnd(fetchKey)
pool.delete(fetchKey)
})
pool.set(fetchKey, fetcher)
return fetcher
} }
const errorLogger = (fetchKey, err, status) => { const errorLogger = (serviceKey, err, status) => {
try { try {
if (status === 'unknown') { if (status === 'unknown') {
// send to sentry
raven && raven.captureException(err, { raven && raven.captureException(err, {
tags: { fetchKey, status, service: fetchKey.split(' ')[0] } tags: {
serviceKey,
service: serviceKey.split(' ')[0],
fetchUrl: err.config.url
}
}) })
// log details err info
const resData = JSON.stringify(err.response.data, null, 2)
const details = err.stack + '\n' + resData.replace(/^/mg, ' > ')
return console.error(fetchKey, `LIVEFN_ERR<${status}>`, details)
} else { } else {
return console.error(fetchKey, `LIVEFN_ERR<${status}>`, err.message) // log known error
printError(serviceKey, status, err)
} }
} catch (e) { } catch (e) {
console.error(fetchKey, `LIVEFN_ERR<${status}>`, err.message) printError(serviceKey, status, err)
console.error(e.message) console.error('ERR_ON_ERR', e.message)
}
}
const printError = (serviceKey, status, err) => {
let details = err.message
if (status === 'unknown') {
details += `\n ${err.stack}`.replace(/^/mg, ' ')
} }
console.error(`LIVE_FN_ERR <${status}> ${serviceKey} > ${err.config.url}\n`, details)
} }

Loading…
Cancel
Save