PageRenderTime 35ms CodeModel.GetById 11ms app.highlight 18ms RepoModel.GetById 2ms app.codeStats 0ms

/deps/npm/lib/utils/error-handler.js

https://github.com/ryanpoplin/node
JavaScript | 343 lines | 291 code | 43 blank | 9 comment | 46 complexity | a59b33f9849cac5f2146dcfeb22e695d MD5 | raw file
  1
  2module.exports = errorHandler
  3
  4var cbCalled = false
  5  , log = require("npmlog")
  6  , npm = require("../npm.js")
  7  , rm = require("rimraf")
  8  , itWorked = false
  9  , path = require("path")
 10  , wroteLogFile = false
 11  , exitCode = 0
 12
 13
 14process.on("exit", function (code) {
 15  // console.error("exit", code)
 16  if (!npm.config.loaded) return
 17  if (code) itWorked = false
 18  if (itWorked) log.info("ok")
 19  else {
 20    if (!cbCalled) {
 21      log.error("", "cb() never called!")
 22    }
 23
 24    if (wroteLogFile) {
 25      log.error("", [""
 26                ,"Additional logging details can be found in:"
 27                ,"    " + path.resolve("npm-debug.log")
 28                ].join("\n"))
 29      wroteLogFile = false
 30    }
 31    log.error("not ok", "code", code)
 32  }
 33
 34  var doExit = npm.config.get("_exit")
 35  if (doExit) {
 36    // actually exit.
 37    if (exitCode === 0 && !itWorked) {
 38      exitCode = 1
 39    }
 40    if (exitCode !== 0) process.exit(exitCode)
 41  } else {
 42    itWorked = false // ready for next exit
 43  }
 44})
 45
 46function exit (code, noLog) {
 47  exitCode = exitCode || process.exitCode || code
 48
 49  var doExit = npm.config.get("_exit")
 50  log.verbose("exit", [code, doExit])
 51  if (log.level === "silent") noLog = true
 52
 53  if (code && !noLog) writeLogFile(reallyExit)
 54  else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })
 55
 56  function reallyExit() {
 57    // truncate once it's been written.
 58    log.record.length = 0
 59
 60    itWorked = !code
 61
 62    // just emit a fake exit event.
 63    // if we're really exiting, then let it exit on its own, so that
 64    // in-process stuff can finish or clean up first.
 65    if (!doExit) process.emit("exit", code)
 66  }
 67}
 68
 69
 70function errorHandler (er) {
 71  var printStack = false
 72  // console.error("errorHandler", er)
 73  if (!npm.config.loaded) {
 74    // logging won't work unless we pretend that it's ready
 75    er = er || new Error("Exit prior to config file resolving.")
 76    console.error(er.stack || er.message)
 77  }
 78
 79  if (cbCalled) {
 80    er = er || new Error("Callback called more than once.")
 81  }
 82
 83  cbCalled = true
 84  if (!er) return exit(0)
 85  if (typeof er === "string") {
 86    log.error("", er)
 87    return exit(1, true)
 88  } else if (!(er instanceof Error)) {
 89    log.error("weird error", er)
 90    return exit(1, true)
 91  }
 92
 93  var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
 94  if (m && !er.code) er.code = m
 95
 96  switch (er.code) {
 97  case "ECONNREFUSED":
 98    log.error("", er)
 99    log.error("", ["\nIf you are behind a proxy, please make sure that the"
100              ,"'proxy' config is set properly.  See: 'npm help config'"
101              ].join("\n"))
102    printStack = true
103    break
104
105  case "EACCES":
106  case "EPERM":
107    log.error("", er)
108    log.error("", ["\nPlease try running this command again as root/Administrator."
109              ].join("\n"))
110    printStack = true
111    break
112
113  case "ELIFECYCLE":
114    er.code = "ELIFECYCLE"
115    log.error("", er.message)
116    log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script."
117              ,"This is most likely a problem with the "+er.pkgname+" package,"
118              ,"not with npm itself."
119              ,"Tell the author that this fails on your system:"
120              ,"    "+er.script
121              ,"You can get their info via:"
122              ,"    npm owner ls "+er.pkgname
123              ,"There is likely additional logging output above."
124              ].join("\n"))
125    break
126
127  case "ENOGIT":
128    er.code = "ENOGIT"
129    log.error("", er.message)
130    log.error("", ["","Failed using git."
131              ,"This is most likely not a problem with npm itself."
132              ,"Please check if you have git installed and in your PATH."
133              ].join("\n"))
134    break
135
136  case "EJSONPARSE":
137    er.code = "EJSONPARSE"
138    log.error("", er.message)
139    log.error("", "File: "+er.file)
140    log.error("", ["Failed to parse package.json data."
141              ,"package.json must be actual JSON, not just JavaScript."
142              ,"","This is not a bug in npm."
143              ,"Tell the package author to fix their package.json file."
144              ].join("\n"), "JSON.parse")
145    break
146
147  case "E404":
148    er.code = "E404"
149    if (er.pkgid && er.pkgid !== "-") {
150      var msg = ["'"+er.pkgid+"' is not in the npm registry."
151                ,"You should bug the author to publish it"]
152      if (er.parent) {
153        msg.push("It was specified as a dependency of '"+er.parent+"'")
154      }
155      if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) {
156        var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "")
157        if (s !== er.pkgid) {
158          s = s.replace(/[^a-z0-9]/g, ' ')
159          msg.push("\nMaybe try 'npm search " + s + "'")
160        }
161      }
162      msg.push("\nNote that you can also install from a"
163              ,"tarball, folder, or http url, or git url.")
164      log.error("404", msg.join("\n"))
165    }
166    break
167
168  case "EPUBLISHCONFLICT":
169    er.code = "EPUBLISHCONFLICT"
170    log.error("publish fail", ["Cannot publish over existing version."
171              ,"Update the 'version' field in package.json and try again."
172              ,""
173              ,"If the previous version was published in error, see:"
174              ,"    npm help unpublish"
175              ,""
176              ,"To automatically increment version numbers, see:"
177              ,"    npm help version"
178              ].join("\n"))
179    break
180
181  case "EISGIT":
182    er.code = "EISGIT"
183    log.error("git", [er.message
184              ,"    "+er.path
185              ,"Refusing to remove it. Update manually,"
186              ,"or move it out of the way first."
187              ].join("\n"))
188    break
189
190  case "ECYCLE":
191    er.code = "ECYCLE"
192    log.error("cycle", [er.message
193              ,"While installing: "+er.pkgid
194              ,"Found a pathological dependency case that npm cannot solve."
195              ,"Please report this to the package author."
196              ].join("\n"))
197    break
198
199  case "EBADPLATFORM":
200    er.code = "EBADPLATFORM"
201    log.error("notsup", [er.message
202              ,"Not compatible with your operating system or architecture: "+er.pkgid
203              ,"Valid OS:    "+er.os.join(",")
204              ,"Valid Arch:  "+er.cpu.join(",")
205              ,"Actual OS:   "+process.platform
206              ,"Actual Arch: "+process.arch
207              ].join("\n"))
208    break
209
210  case "EEXIST":
211    log.error([er.message
212              ,"File exists: "+er.path
213              ,"Move it away, and try again."].join("\n"))
214    break
215
216  case "ENEEDAUTH":
217    log.error("need auth", [er.message
218              ,"You need to authorize this machine using `npm adduser`"
219              ].join("\n"))
220    break
221
222  case "EPEERINVALID":
223    var peerErrors = Object.keys(er.peersDepending).map(function (peer) {
224      return "Peer " + peer + " wants " + er.packageName + "@"
225        + er.peersDepending[peer]
226    })
227    log.error("peerinvalid", [er.message].concat(peerErrors).join("\n"))
228    break
229
230  case "ECONNRESET":
231  case "ENOTFOUND":
232  case "ETIMEDOUT":
233    log.error("network", [er.message
234              ,"This is most likely not a problem with npm itself"
235              ,"and is related to network connectivity."
236              ,"In most cases you are behind a proxy or have bad network settings."
237              ,"\nIf you are behind a proxy, please make sure that the"
238              ,"'proxy' config is set properly.  See: 'npm help config'"
239              ].join("\n"))
240    break
241
242  case "ENOPACKAGEJSON":
243    log.error("package.json", [er.message
244              ,"This is most likely not a problem with npm itself."
245              ,"npm can't find a package.json file in your current directory."
246              ].join("\n"))
247    break
248
249  case "ETARGET":
250    log.error("notarget", [er.message
251              ,"This is most likely not a problem with npm itself."
252              ,"In most cases you or one of your dependencies are requesting"
253              ,"a package version that doesn't exist."
254              ].join("\n"))
255    break
256
257  case "ENOTSUP":
258    if (er.required) {
259      log.error("notsup", [er.message
260                ,"Not compatible with your version of node/npm: "+er.pkgid
261                ,"Required: "+JSON.stringify(er.required)
262                ,"Actual:   "
263                +JSON.stringify({npm:npm.version
264                                ,node:npm.config.get("node-version")})
265                ].join("\n"))
266      break
267    } // else passthrough
268
269  default:
270    log.error("", er.stack || er.message || er)
271    log.error("", ["If you need help, you may report this *entire* log,"
272                  ,"including the npm and node versions, at:"
273                  ,"    <http://github.com/npm/npm/issues>"
274                  ].join("\n"))
275    printStack = false
276    break
277  }
278
279  var os = require("os")
280  // just a line break
281  console.error("")
282  log.error("System", os.type() + " " + os.release())
283  log.error("command", process.argv
284            .map(JSON.stringify).join(" "))
285  log.error("cwd", process.cwd())
286  log.error("node -v", process.version)
287  log.error("npm -v", npm.version)
288
289  ; [ "file"
290    , "path"
291    , "type"
292    , "syscall"
293    , "fstream_path"
294    , "fstream_unc_path"
295    , "fstream_type"
296    , "fstream_class"
297    , "fstream_finish_call"
298    , "fstream_linkpath"
299    , "code"
300    , "errno"
301    , "stack"
302    , "fstream_stack"
303    ].forEach(function (k) {
304      var v = er[k]
305      if (k === "stack") {
306        if (!printStack) return
307        if (!v) v = er.message
308      }
309      if (!v) return
310      if (k === "fstream_stack") v = v.join("\n")
311      log.error(k, v)
312    })
313
314  exit(typeof er.errno === "number" ? er.errno : 1)
315}
316
317var writingLogFile = false
318function writeLogFile (cb) {
319  if (writingLogFile) return cb()
320  writingLogFile = true
321  wroteLogFile = true
322
323  var fs = require("graceful-fs")
324    , fstr = fs.createWriteStream("npm-debug.log")
325    , util = require("util")
326    , os = require("os")
327    , out = ""
328
329  log.record.forEach(function (m) {
330    var pref = [m.id, m.level]
331    if (m.prefix) pref.push(m.prefix)
332    pref = pref.join(' ')
333
334    m.message.trim().split(/\r?\n/).map(function (line) {
335      return (pref + ' ' + line).trim()
336    }).forEach(function (line) {
337      out += line + os.EOL
338    })
339  })
340
341  fstr.end(out)
342  fstr.on("close", cb)
343}