error.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. const {signalsByName} = require('human-signals');
  3. const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
  4. if (timedOut) {
  5. return `timed out after ${timeout} milliseconds`;
  6. }
  7. if (isCanceled) {
  8. return 'was canceled';
  9. }
  10. if (errorCode !== undefined) {
  11. return `failed with ${errorCode}`;
  12. }
  13. if (signal !== undefined) {
  14. return `was killed with ${signal} (${signalDescription})`;
  15. }
  16. if (exitCode !== undefined) {
  17. return `failed with exit code ${exitCode}`;
  18. }
  19. return 'failed';
  20. };
  21. const makeError = ({
  22. stdout,
  23. stderr,
  24. all,
  25. error,
  26. signal,
  27. exitCode,
  28. command,
  29. escapedCommand,
  30. timedOut,
  31. isCanceled,
  32. killed,
  33. parsed: {options: {timeout}}
  34. }) => {
  35. // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
  36. // We normalize them to `undefined`
  37. exitCode = exitCode === null ? undefined : exitCode;
  38. signal = signal === null ? undefined : signal;
  39. const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
  40. const errorCode = error && error.code;
  41. const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
  42. const execaMessage = `Command ${prefix}: ${command}`;
  43. const isError = Object.prototype.toString.call(error) === '[object Error]';
  44. const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
  45. const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
  46. if (isError) {
  47. error.originalMessage = error.message;
  48. error.message = message;
  49. } else {
  50. error = new Error(message);
  51. }
  52. error.shortMessage = shortMessage;
  53. error.command = command;
  54. error.escapedCommand = escapedCommand;
  55. error.exitCode = exitCode;
  56. error.signal = signal;
  57. error.signalDescription = signalDescription;
  58. error.stdout = stdout;
  59. error.stderr = stderr;
  60. if (all !== undefined) {
  61. error.all = all;
  62. }
  63. if ('bufferedData' in error) {
  64. delete error.bufferedData;
  65. }
  66. error.failed = true;
  67. error.timedOut = Boolean(timedOut);
  68. error.isCanceled = isCanceled;
  69. error.killed = killed && !timedOut;
  70. return error;
  71. };
  72. module.exports = makeError;