Browse Source

chore: better error log

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

68
libs/live-fetcher.js

@ -3,26 +3,18 @@ const pool = require('./live-pool.js')
const raven = require('./raven.js')
module.exports = async (scope, fn, paramsPath) => {
const fetchKey = `#${scope} ${paramsPath}`
const fetchKey = `#${scope}/${paramsPath}`
if (pool.has(fetchKey)) return pool.get(fetchKey)
console.time(fetchKey)
const fetchStart = new Date()
const fetcher = fn(...paramsPath.split('/')).then(
result => typeof result === 'object' ? result : { failed: true },
err => {
let status = 'unknown'
if (err.response && err.response.status === 404) {
status = 'not found'
} else if (err.code === 'ECONNABORTED') {
status = 'timeout'
}
errorLogger(fetchKey, err, status)
return { status, failed: true }
}).finally(() => {
console.timeEnd(fetchKey)
result => {
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)
@ -30,21 +22,45 @@ module.exports = async (scope, fn, paramsPath) => {
return fetcher
}
const errorLogger = (fetchKey, err, status) => {
const errorHandler = (scope, paramsPath, err) => {
let status = 'unknown'
if (err.response && err.response.status === 404) {
status = 'not found'
} else if (err.code === 'ECONNABORTED') {
status = 'timeout'
}
errorLogger(`/${scope}/${paramsPath}`, err, status)
return { status, failed: true }
}
const errorLogger = (serviceKey, err, status) => {
try {
if (status === 'unknown') {
// send to sentry
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 {
return console.error(fetchKey, `LIVEFN_ERR<${status}>`, err.message)
// log known error
printError(serviceKey, status, err)
}
} catch (e) {
console.error(fetchKey, `LIVEFN_ERR<${status}>`, err.message)
console.error(e.message)
printError(serviceKey, status, err)
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