error-handler.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. module.exports = errorHandler
  2. module.exports.exit = exit
  3. var cbCalled = false
  4. var log = require('npmlog')
  5. var npm = require('../npm.js')
  6. var itWorked = false
  7. var path = require('path')
  8. var wroteLogFile = false
  9. var exitCode = 0
  10. var rollbacks = npm.rollbacks
  11. var chain = require('slide').chain
  12. var errorMessage = require('./error-message.js')
  13. var replaceInfo = require('./replace-info.js')
  14. var stopMetrics = require('./metrics.js').stop
  15. const cacheFile = require('./cache-file.js')
  16. var logFileName
  17. function getLogFile () {
  18. if (!logFileName) {
  19. logFileName = path.resolve(npm.config.get('cache'), '_logs', (new Date()).toISOString().replace(/[.:]/g, '_') + '-debug.log')
  20. }
  21. return logFileName
  22. }
  23. var timings = {
  24. version: npm.version,
  25. command: process.argv.slice(2),
  26. logfile: null
  27. }
  28. process.on('timing', function (name, value) {
  29. if (timings[name]) { timings[name] += value } else { timings[name] = value }
  30. })
  31. process.on('exit', function (code) {
  32. process.emit('timeEnd', 'npm')
  33. log.disableProgress()
  34. if (npm.config && npm.config.loaded && npm.config.get('timing')) {
  35. try {
  36. timings.logfile = getLogFile()
  37. cacheFile.append('_timing.json', JSON.stringify(timings) + '\n')
  38. } catch (_) {
  39. // ignore
  40. }
  41. }
  42. // kill any outstanding stats reporter if it hasn't finished yet
  43. stopMetrics()
  44. if (code) itWorked = false
  45. if (itWorked) {
  46. log.info('ok')
  47. } else {
  48. if (!cbCalled) {
  49. log.error('', 'cb() never called!')
  50. console.error('')
  51. log.error('', 'This is an error with npm itself. Please report this error at:')
  52. log.error('', ' <https://npm.community>')
  53. writeLogFile()
  54. }
  55. if (code) {
  56. log.verbose('code', code)
  57. }
  58. }
  59. if (npm.config && npm.config.loaded && npm.config.get('timing') && !wroteLogFile) writeLogFile()
  60. if (wroteLogFile) {
  61. // just a line break
  62. if (log.levels[log.level] <= log.levels.error) console.error('')
  63. log.error(
  64. '',
  65. [
  66. 'A complete log of this run can be found in:',
  67. ' ' + getLogFile()
  68. ].join('\n')
  69. )
  70. wroteLogFile = false
  71. }
  72. var doExit = npm.config && npm.config.loaded && npm.config.get('_exit')
  73. if (doExit) {
  74. // actually exit.
  75. if (exitCode === 0 && !itWorked) {
  76. exitCode = 1
  77. }
  78. if (exitCode !== 0) process.exit(exitCode)
  79. } else {
  80. itWorked = false // ready for next exit
  81. }
  82. })
  83. function exit (code, noLog) {
  84. exitCode = exitCode || process.exitCode || code
  85. var doExit = npm.config && npm.config.loaded ? npm.config.get('_exit') : true
  86. log.verbose('exit', [code, doExit])
  87. if (log.level === 'silent') noLog = true
  88. if (rollbacks.length) {
  89. chain(rollbacks.map(function (f) {
  90. return function (cb) {
  91. npm.commands.unbuild([f], true, cb)
  92. }
  93. }), function (er) {
  94. if (er) {
  95. log.error('error rolling back', er)
  96. if (!code) {
  97. errorHandler(er)
  98. } else {
  99. if (!noLog) writeLogFile()
  100. reallyExit(er)
  101. }
  102. } else {
  103. if (!noLog && code) writeLogFile()
  104. reallyExit()
  105. }
  106. })
  107. rollbacks.length = 0
  108. } else if (code && !noLog) {
  109. writeLogFile()
  110. } else {
  111. reallyExit()
  112. }
  113. function reallyExit (er) {
  114. if (er && !code) code = typeof er.errno === 'number' ? er.errno : 1
  115. itWorked = !code
  116. // Exit directly -- nothing in the CLI should still be running in the
  117. // background at this point, and this makes sure anything left dangling
  118. // for whatever reason gets thrown away, instead of leaving the CLI open
  119. //
  120. // Commands that expect long-running actions should just delay `cb()`
  121. process.stdout.write('', () => {
  122. process.exit(code)
  123. })
  124. }
  125. }
  126. function errorHandler (er) {
  127. log.disableProgress()
  128. if (!npm.config || !npm.config.loaded) {
  129. // logging won't work unless we pretend that it's ready
  130. er = er || new Error('Exit prior to config file resolving.')
  131. console.error(er.stack || er.message)
  132. }
  133. if (cbCalled) {
  134. er = er || new Error('Callback called more than once.')
  135. }
  136. cbCalled = true
  137. if (!er) return exit(0)
  138. if (typeof er === 'string') {
  139. log.error('', er)
  140. return exit(1, true)
  141. } else if (!(er instanceof Error)) {
  142. log.error('weird error', er)
  143. return exit(1, true)
  144. }
  145. var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
  146. if (m && !er.code) {
  147. er.code = m
  148. }
  149. ;[
  150. 'type',
  151. 'stack',
  152. 'statusCode',
  153. 'pkgid'
  154. ].forEach(function (k) {
  155. var v = er[k]
  156. if (!v) return
  157. v = replaceInfo(v)
  158. log.verbose(k, v)
  159. })
  160. log.verbose('cwd', process.cwd())
  161. var os = require('os')
  162. var args = replaceInfo(process.argv)
  163. log.verbose('', os.type() + ' ' + os.release())
  164. log.verbose('argv', args.map(JSON.stringify).join(' '))
  165. log.verbose('node', process.version)
  166. log.verbose('npm ', 'v' + npm.version)
  167. ;[
  168. 'code',
  169. 'syscall',
  170. 'file',
  171. 'path',
  172. 'dest',
  173. 'errno'
  174. ].forEach(function (k) {
  175. var v = er[k]
  176. if (v) log.error(k, v)
  177. })
  178. var msg = errorMessage(er)
  179. msg.summary.concat(msg.detail).forEach(function (errline) {
  180. log.error.apply(log, errline)
  181. })
  182. if (npm.config && npm.config.get('json')) {
  183. var error = {
  184. error: {
  185. code: er.code,
  186. summary: messageText(msg.summary),
  187. detail: messageText(msg.detail)
  188. }
  189. }
  190. console.log(JSON.stringify(error, null, 2))
  191. }
  192. exit(typeof er.errno === 'number' ? er.errno : 1)
  193. }
  194. function messageText (msg) {
  195. return msg.map(function (line) {
  196. return line.slice(1).join(' ')
  197. }).join('\n')
  198. }
  199. function writeLogFile () {
  200. if (wroteLogFile) return
  201. var os = require('os')
  202. try {
  203. var logOutput = ''
  204. log.record.forEach(function (m) {
  205. var pref = [m.id, m.level]
  206. if (m.prefix) pref.push(m.prefix)
  207. pref = pref.join(' ')
  208. m.message.trim().split(/\r?\n/).map(function (line) {
  209. return (pref + ' ' + line).trim()
  210. }).forEach(function (line) {
  211. logOutput += line + os.EOL
  212. })
  213. })
  214. cacheFile.write(getLogFile(), logOutput)
  215. // truncate once it's been written.
  216. log.record.length = 0
  217. wroteLogFile = true
  218. } catch (ex) {
  219. }
  220. }