error-message.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. 'use strict'
  2. var npm = require('../npm.js')
  3. var util = require('util')
  4. var nameValidator = require('validate-npm-package-name')
  5. var npmlog = require('npmlog')
  6. var replaceInfo = require('./replace-info.js')
  7. module.exports = errorMessage
  8. function errorMessage (er) {
  9. var short = []
  10. var detail = []
  11. er.message = replaceInfo(er.message)
  12. er.stack = replaceInfo(er.stack)
  13. switch (er.code) {
  14. case 'ENOAUDIT':
  15. short.push(['audit', er.message])
  16. break
  17. case 'EAUDITNOPJSON':
  18. short.push(['audit', er.message])
  19. break
  20. case 'EAUDITNOLOCK':
  21. short.push(['audit', er.message])
  22. detail.push(['audit', 'Try creating one first with: npm i --package-lock-only'])
  23. break
  24. case 'ECONNREFUSED':
  25. short.push(['', er])
  26. detail.push([
  27. '',
  28. [
  29. '\nIf you are behind a proxy, please make sure that the',
  30. "'proxy' config is set properly. See: 'npm help config'"
  31. ].join('\n')
  32. ])
  33. break
  34. case 'EACCES':
  35. case 'EPERM':
  36. const isCachePath = typeof er.path === 'string' &&
  37. npm.config && er.path.startsWith(npm.config.get('cache'))
  38. const isCacheDest = typeof er.dest === 'string' &&
  39. npm.config && er.dest.startsWith(npm.config.get('cache'))
  40. const isWindows = process.platform === 'win32'
  41. if (!isWindows && (isCachePath || isCacheDest)) {
  42. // user probably doesn't need this, but still add it to the debug log
  43. npmlog.verbose(er.stack)
  44. short.push([
  45. '',
  46. [
  47. '',
  48. 'Your cache folder contains root-owned files, due to a bug in',
  49. 'previous versions of npm which has since been addressed.',
  50. '',
  51. 'To permanently fix this problem, please run:',
  52. ` sudo chown -R ${process.getuid()}:${process.getgid()} ${JSON.stringify(npm.config.get('cache'))}`
  53. ].join('\n')
  54. ])
  55. } else {
  56. short.push(['', er])
  57. detail.push([
  58. '',
  59. [
  60. '\nThe operation was rejected by your operating system.',
  61. (process.platform === 'win32'
  62. ? 'It\'s possible that the file was already in use (by a text editor or antivirus),\n' +
  63. 'or that you lack permissions to access it.'
  64. : 'It is likely you do not have the permissions to access this file as the current user'),
  65. '\nIf you believe this might be a permissions issue, please double-check the',
  66. 'permissions of the file and its containing directories, or try running',
  67. 'the command again as root/Administrator.'
  68. ].join('\n')])
  69. }
  70. break
  71. case 'EUIDLOOKUP':
  72. short.push(['lifecycle', er.message])
  73. detail.push([
  74. '',
  75. [
  76. '',
  77. 'Failed to look up the user/group for running scripts.',
  78. '',
  79. 'Try again with a different --user or --group settings, or',
  80. 'run with --unsafe-perm to execute scripts as root.'
  81. ].join('\n')
  82. ])
  83. break
  84. case 'ELIFECYCLE':
  85. short.push(['', er.message])
  86. detail.push([
  87. '',
  88. [
  89. '',
  90. 'Failed at the ' + er.pkgid + ' ' + er.stage + ' script.',
  91. 'This is probably not a problem with npm. There is likely additional logging output above.'
  92. ].join('\n')]
  93. )
  94. break
  95. case 'ENOGIT':
  96. short.push(['', er.message])
  97. detail.push([
  98. '',
  99. [
  100. '',
  101. 'Failed using git.',
  102. 'Please check if you have git installed and in your PATH.'
  103. ].join('\n')
  104. ])
  105. break
  106. case 'EJSONPARSE':
  107. const path = require('path')
  108. // Check whether we ran into a conflict in our own package.json
  109. if (er.file === path.join(npm.prefix, 'package.json')) {
  110. const isDiff = require('../install/read-shrinkwrap.js')._isDiff
  111. const txt = require('fs').readFileSync(er.file, 'utf8')
  112. if (isDiff(txt)) {
  113. detail.push([
  114. '',
  115. [
  116. 'Merge conflict detected in your package.json.',
  117. '',
  118. 'Please resolve the package.json conflict and retry the command:',
  119. '',
  120. `$ ${process.argv.join(' ')}`
  121. ].join('\n')
  122. ])
  123. break
  124. }
  125. }
  126. short.push(['JSON.parse', er.message])
  127. detail.push([
  128. 'JSON.parse',
  129. [
  130. 'Failed to parse package.json data.',
  131. 'package.json must be actual JSON, not just JavaScript.'
  132. ].join('\n')
  133. ])
  134. break
  135. case 'EOTP':
  136. case 'E401':
  137. // E401 is for places where we accidentally neglect OTP stuff
  138. if (er.code === 'EOTP' || /one-time pass/.test(er.message)) {
  139. short.push(['', 'This operation requires a one-time password from your authenticator.'])
  140. detail.push([
  141. '',
  142. [
  143. 'You can provide a one-time password by passing --otp=<code> to the command you ran.',
  144. 'If you already provided a one-time password then it is likely that you either typoed',
  145. 'it, or it timed out. Please try again.'
  146. ].join('\n')
  147. ])
  148. } else {
  149. // npm ERR! code E401
  150. // npm ERR! Unable to authenticate, need: Basic
  151. const auth = (er.headers && er.headers['www-authenticate'] && er.headers['www-authenticate'].map((au) => au.split(/,\s*/))[0]) || []
  152. if (auth.indexOf('Bearer') !== -1) {
  153. short.push(['', 'Unable to authenticate, your authentication token seems to be invalid.'])
  154. detail.push([
  155. '',
  156. [
  157. 'To correct this please trying logging in again with:',
  158. ' npm login'
  159. ].join('\n')
  160. ])
  161. } else if (auth.indexOf('Basic') !== -1) {
  162. short.push(['', 'Incorrect or missing password.'])
  163. detail.push([
  164. '',
  165. [
  166. 'If you were trying to login, change your password, create an',
  167. 'authentication token or enable two-factor authentication then',
  168. 'that means you likely typed your password in incorrectly.',
  169. 'Please try again, or recover your password at:',
  170. ' https://www.npmjs.com/forgot',
  171. '',
  172. 'If you were doing some other operation then your saved credentials are',
  173. 'probably out of date. To correct this please try logging in again with:',
  174. ' npm login'
  175. ].join('\n')
  176. ])
  177. } else {
  178. short.push(['', er.message || er])
  179. }
  180. }
  181. break
  182. case 'E404':
  183. // There's no need to have 404 in the message as well.
  184. var msg = er.message.replace(/^404\s+/, '')
  185. short.push(['404', msg])
  186. if (er.pkgid && er.pkgid !== '-') {
  187. var pkg = er.pkgid.replace(/(?!^)@.*$/, '')
  188. detail.push(['404', ''])
  189. detail.push(['404', '', "'" + er.pkgid + "' is not in the npm registry."])
  190. var valResult = nameValidator(pkg)
  191. if (valResult.validForNewPackages) {
  192. detail.push(['404', 'You should bug the author to publish it (or use the name yourself!)'])
  193. } else {
  194. detail.push(['404', 'Your package name is not valid, because', ''])
  195. var errorsArray = (valResult.errors || []).concat(valResult.warnings || [])
  196. errorsArray.forEach(function (item, idx) {
  197. detail.push(['404', ' ' + (idx + 1) + '. ' + item])
  198. })
  199. }
  200. if (er.parent) {
  201. detail.push(['404', "It was specified as a dependency of '" + er.parent + "'"])
  202. }
  203. detail.push(['404', '\nNote that you can also install from a'])
  204. detail.push(['404', 'tarball, folder, http url, or git url.'])
  205. }
  206. break
  207. case 'EPUBLISHCONFLICT':
  208. short.push(['publish fail', 'Cannot publish over existing version.'])
  209. detail.push(['publish fail', "Update the 'version' field in package.json and try again."])
  210. detail.push(['publish fail', ''])
  211. detail.push(['publish fail', 'To automatically increment version numbers, see:'])
  212. detail.push(['publish fail', ' npm help version'])
  213. break
  214. case 'EISGIT':
  215. short.push(['git', er.message])
  216. short.push(['git', ' ' + er.path])
  217. detail.push([
  218. 'git',
  219. [
  220. 'Refusing to remove it. Update manually,',
  221. 'or move it out of the way first.'
  222. ].join('\n')
  223. ])
  224. break
  225. case 'ECYCLE':
  226. short.push([
  227. 'cycle',
  228. [
  229. er.message,
  230. 'While installing: ' + er.pkgid
  231. ].join('\n')
  232. ])
  233. detail.push([
  234. 'cycle',
  235. [
  236. 'Found a pathological dependency case that npm cannot solve.',
  237. 'Please report this to the package author.'
  238. ].join('\n')
  239. ])
  240. break
  241. case 'EBADPLATFORM':
  242. var validOs = er.os.join ? er.os.join(',') : er.os
  243. var validArch = er.cpu.join ? er.cpu.join(',') : er.cpu
  244. var expected = {os: validOs, arch: validArch}
  245. var actual = {os: process.platform, arch: process.arch}
  246. short.push([
  247. 'notsup',
  248. [
  249. util.format('Unsupported platform for %s: wanted %j (current: %j)', er.pkgid, expected, actual)
  250. ].join('\n')
  251. ])
  252. detail.push([
  253. 'notsup',
  254. [
  255. 'Valid OS: ' + validOs,
  256. 'Valid Arch: ' + validArch,
  257. 'Actual OS: ' + process.platform,
  258. 'Actual Arch: ' + process.arch
  259. ].join('\n')
  260. ])
  261. break
  262. case 'EEXIST':
  263. short.push(['', er.message])
  264. short.push(['', 'File exists: ' + (er.dest || er.path)])
  265. detail.push(['', 'Remove the existing file and try again, or run npm'])
  266. detail.push(['', 'with --force to overwrite files recklessly.'])
  267. break
  268. case 'ENEEDAUTH':
  269. short.push(['need auth', er.message])
  270. detail.push(['need auth', 'You need to authorize this machine using `npm adduser`'])
  271. break
  272. case 'ECONNRESET':
  273. case 'ENOTFOUND':
  274. case 'ETIMEDOUT':
  275. case 'EAI_FAIL':
  276. short.push(['network', er.message])
  277. detail.push([
  278. 'network',
  279. [
  280. 'This is a problem related to network connectivity.',
  281. 'In most cases you are behind a proxy or have bad network settings.',
  282. '\nIf you are behind a proxy, please make sure that the',
  283. "'proxy' config is set properly. See: 'npm help config'"
  284. ].join('\n')
  285. ])
  286. break
  287. case 'ENOPACKAGEJSON':
  288. short.push(['package.json', er.message])
  289. detail.push([
  290. 'package.json',
  291. [
  292. "npm can't find a package.json file in your current directory."
  293. ].join('\n')
  294. ])
  295. break
  296. case 'ETARGET':
  297. short.push(['notarget', er.message])
  298. msg = [
  299. 'In most cases you or one of your dependencies are requesting',
  300. "a package version that doesn't exist."
  301. ]
  302. if (er.parent) {
  303. msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
  304. }
  305. detail.push(['notarget', msg.join('\n')])
  306. break
  307. case 'E403':
  308. short.push(['403', er.message])
  309. msg = [
  310. 'In most cases, you or one of your dependencies are requesting',
  311. 'a package version that is forbidden by your security policy.'
  312. ]
  313. if (er.parent) {
  314. msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
  315. }
  316. detail.push(['403', msg.join('\n')])
  317. break
  318. case 'ENOTSUP':
  319. if (er.required) {
  320. short.push(['notsup', er.message])
  321. short.push(['notsup', 'Not compatible with your version of node/npm: ' + er.pkgid])
  322. detail.push([
  323. 'notsup',
  324. [
  325. 'Not compatible with your version of node/npm: ' + er.pkgid,
  326. 'Required: ' + JSON.stringify(er.required),
  327. 'Actual: ' + JSON.stringify({
  328. npm: npm.version,
  329. node: npm.config.get('node-version')
  330. })
  331. ].join('\n')
  332. ])
  333. break
  334. } // else passthrough
  335. /* eslint no-fallthrough:0 */
  336. case 'ENOSPC':
  337. short.push(['nospc', er.message])
  338. detail.push([
  339. 'nospc',
  340. [
  341. 'There appears to be insufficient space on your system to finish.',
  342. 'Clear up some disk space and try again.'
  343. ].join('\n')
  344. ])
  345. break
  346. case 'EROFS':
  347. short.push(['rofs', er.message])
  348. detail.push([
  349. 'rofs',
  350. [
  351. 'Often virtualized file systems, or other file systems',
  352. "that don't support symlinks, give this error."
  353. ].join('\n')
  354. ])
  355. break
  356. case 'ENOENT':
  357. short.push(['enoent', er.message])
  358. detail.push([
  359. 'enoent',
  360. [
  361. 'This is related to npm not being able to find a file.',
  362. er.file ? "\nCheck if the file '" + er.file + "' is present." : ''
  363. ].join('\n')
  364. ])
  365. break
  366. case 'EMISSINGARG':
  367. case 'EUNKNOWNTYPE':
  368. case 'EINVALIDTYPE':
  369. case 'ETOOMANYARGS':
  370. short.push(['typeerror', er.stack])
  371. detail.push([
  372. 'typeerror',
  373. [
  374. 'This is an error with npm itself. Please report this error at:',
  375. ' <https://npm.community>'
  376. ].join('\n')
  377. ])
  378. break
  379. default:
  380. short.push(['', er.message || er])
  381. break
  382. }
  383. if (er.optional) {
  384. short.unshift(['optional', er.optional + ' (' + er.location + '):'])
  385. short.concat(detail).forEach(function (msg) {
  386. if (!msg[0]) msg[0] = 'optional'
  387. if (msg[1]) msg[1] = msg[1].toString().replace(/(^|\n)/g, '$1SKIPPING OPTIONAL DEPENDENCY: ')
  388. })
  389. }
  390. return {summary: short, detail: detail}
  391. }