Bug 1544284 - toolkit/ automated ESLint no-throw-literal fixes. r=Standard8

Result of running:
$ mach eslint -funix toolkit/ | sed -Ee 's/:.+//' - | xargs sed -E \
    -e 's/throw ((["`])[^"]+\2);/throw new Error(\1);/g' \
    -e 's/throw ((["`])[^"]+\2 \+ [^ ";]+);/throw new Error(\1);/g' \
    -e 's/throw \(/throw new Error(/g' -i

...and then reverting a couple of places where comments were touched,
as well as changes to toolkit/components/ctypes/tests/unit/test_jsctypes.js
that required expectation changes to
toolkit/components/ctypes/tests/chrome/test_ctypes.xul

Differential Revision: https://phabricator.services.mozilla.com/D27448

--HG--
extra : moz-landing-system : lando
This commit is contained in:
Ian Moody 2019-04-16 19:30:27 +00:00
Родитель d09a048d2a
Коммит 57b82dd9be
28 изменённых файлов: 52 добавлений и 52 удалений

Просмотреть файл

@ -1293,7 +1293,7 @@ TreeNode.prototype = {
case UNITS_COUNT_CUMULATIVE: return formatNum(this._amount);
case UNITS_PERCENTAGE: return formatPercentage(this._amount);
default:
throw "Invalid memory report(s): bad units in TreeNode.toString";
throw new Error("Invalid memory report(s): bad units in TreeNode.toString");
}
},
};

Просмотреть файл

@ -38,7 +38,7 @@ function fakeUIResponse() {
if (topic === "captive-portal-login-success") {
loginSuccessCount++;
if (loginSuccessCount > 1) {
throw "We should only receive 'captive-portal-login-success' once";
throw new Error("We should only receive 'captive-portal-login-success' once");
}
Assert.equal(++step, 4);
}

Просмотреть файл

@ -12,7 +12,7 @@ XPCOMUtils.defineLazyServiceGetter(this, "serviceWorkerManager",
"nsIServiceWorkerManager");
if (Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_CONTENT) {
throw "ServiceWorkerCleanUp.jsm can only be used in the parent process";
throw new Error("ServiceWorkerCleanUp.jsm can only be used in the parent process");
}
this.EXPORTED_SYMBOLS = ["ServiceWorkerCleanUp"];

Просмотреть файл

@ -21,7 +21,7 @@ async function check_keyword(aURI, aKeyword) {
} else {
let entry = await PlacesUtils.keywords.fetch({ url: aURI });
if (entry) {
throw (`${aURI.spec} should not have a keyword`);
throw new Error(`${aURI.spec} should not have a keyword`);
}
}
}

Просмотреть файл

@ -148,7 +148,7 @@ function readFileData(aFile) {
let size = inputStream.available();
let bytes = readInputStreamData(inputStream);
if (size != bytes.length) {
throw "Didn't read expected number of bytes";
throw new Error("Didn't read expected number of bytes");
}
return bytes;
}

Просмотреть файл

@ -29,11 +29,11 @@ MainProcessSingleton.prototype = {
let isWeb = ["https", "http", "ftp"];
if (!isWeb.includes(engineURL.scheme))
throw "Unsupported search engine URL: " + engineURL.spec;
throw new Error("Unsupported search engine URL: " + engineURL.spec);
if (Services.policies &&
!Services.policies.isAllowed("installSearchEngine")) {
throw "Search Engine installation blocked by the Enterprise Policy Manager.";
throw new Error("Search Engine installation blocked by the Enterprise Policy Manager.");
}
} catch (ex) {
Cu.reportError("Invalid argument passed to window.external.AddSearchProvider: " + ex);

Просмотреть файл

@ -163,7 +163,7 @@ var TabModalPrompt = class {
this.onCloseCallback = onCloseCallback;
if (args.enableDelay)
throw "BUTTON_DELAY_ENABLE not yet supported for tab-modal prompts";
throw new Error("BUTTON_DELAY_ENABLE not yet supported for tab-modal prompts");
// We need to remove the prompt when the tab or browser window is closed or
// the page navigates, else we never unwind the event loop and that's sad times.

Просмотреть файл

@ -51,7 +51,7 @@ CommonDialog.prototype = {
if (this.args.button3Label)
numButtons++;
if (numButtons == 0)
throw "A dialog with no buttons? Can not haz.";
throw new Error("A dialog with no buttons? Can not haz.");
this.numButtons = numButtons;
this.hasInputField = false;
this.iconClass = ["question-icon"];
@ -82,7 +82,7 @@ CommonDialog.prototype = {
break;
default:
Cu.reportError("commonDialog opened for unknown type: " + this.args.promptType);
throw "unknown dialog type";
throw new Error("unknown dialog type");
}
if (xulDialog) {

Просмотреть файл

@ -211,11 +211,11 @@ var PromptUtilsTemp = {
// channel's actual destination.
if (aAuthInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) {
if (!(aChannel instanceof Ci.nsIProxiedChannel))
throw "proxy auth needs nsIProxiedChannel";
throw new Error("proxy auth needs nsIProxiedChannel");
let info = aChannel.proxyInfo;
if (!info)
throw "proxy auth needs nsIProxyInfo";
throw new Error("proxy auth needs nsIProxyInfo");
// Proxies don't have a scheme, but we'll use "moz-proxy://"
// so that it's more obvious what the login is for.
@ -314,7 +314,7 @@ PromptUtils = PromptUtilsTemp;
XPCOMUtils.defineLazyGetter(PromptUtils, "strBundle", function() {
let bundle = Services.strings.createBundle("chrome://global/locale/commonDialogs.properties");
if (!bundle)
throw "String bundle for Prompter not present!";
throw new Error("String bundle for Prompter not present!");
return bundle;
});

Просмотреть файл

@ -209,7 +209,7 @@ function dismissPrompt(ui, action) {
break;
default:
throw "dismissPrompt action listed unknown button.";
throw new Error("dismissPrompt action listed unknown button.");
}
}

Просмотреть файл

@ -2774,7 +2774,7 @@ SearchService.prototype = {
try {
if (!cache.engines.length)
throw "cannot write without any engine.";
throw new Error("cannot write without any engine.");
LOG("_buildCache: Writing to cache file.");
let path = OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME);
@ -3062,7 +3062,7 @@ SearchService.prototype = {
let bytes = await OS.File.read(cacheFilePath, {compression: "lz4"});
json = JSON.parse(new TextDecoder().decode(bytes));
if (!json.engines || !json.engines.length)
throw "no engine in the file";
throw new Error("no engine in the file");
// Reset search default expiration on major releases
if (json.appVersion != Services.appinfo.version &&
geoSpecificDefaultsEnabled() &&

Просмотреть файл

@ -516,7 +516,7 @@ function getWindowsVersionInfo() {
winVer.dwOSVersionInfoSize = OSVERSIONINFOEXW.size;
if (0 === GetVersionEx(winVer.address())) {
throw ("Failure in GetVersionEx (returned 0)");
throw new Error("Failure in GetVersionEx (returned 0)");
}
return {

Просмотреть файл

@ -159,7 +159,7 @@ function saveImageURL(aURL, aFileName, aFilePickerTitleKey, aShouldBypassCache,
// whether in-process or out-of-process.
function saveBrowser(aBrowser, aSkipPrompt, aOuterWindowID = 0) {
if (!aBrowser) {
throw "Must have a browser when calling saveBrowser";
throw new Error("Must have a browser when calling saveBrowser");
}
let persistable = aBrowser.frameLoader;
// Because of how pdf.js deals with principals, saving the document the "normal"
@ -202,7 +202,7 @@ function saveBrowser(aBrowser, aSkipPrompt, aOuterWindowID = 0) {
// command (bug 1141337) and pre-e10s add-ons.
function saveDocument(aDocument, aSkipPrompt) {
if (!aDocument)
throw "Must have a document when calling saveDocument";
throw new Error("Must have a document when calling saveDocument");
let contentDisposition = null;
let cacheKey = 0;

Просмотреть файл

@ -111,7 +111,7 @@ MozElements.NotificationBox = class NotificationBox {
aEventCallback, aNotificationIs) {
if (aPriority < this.PRIORITY_INFO_LOW ||
aPriority > this.PRIORITY_CRITICAL_HIGH)
throw "Invalid notification priority " + aPriority;
throw new Error("Invalid notification priority " + aPriority);
// check for where the notification should be inserted according to
// priority. If two are equal, the existing one appears on top.

Просмотреть файл

@ -274,7 +274,7 @@ var ClientIDImpl = {
async setClientID(id) {
if (!this.updateClientID(id)) {
throw ("Invalid client ID: " + id);
throw new Error("Invalid client ID: " + id);
}
this._saveClientIdTask = this._saveClientID();

Просмотреть файл

@ -149,7 +149,7 @@ Rect.prototype = {
center: function center() {
if (this.isEmpty())
throw "Empty rectangles do not have centers";
throw new Error("Empty rectangles do not have centers");
return new Point(this.left + (this.right - this.left) / 2,
this.top + (this.bottom - this.top) / 2);
},

Просмотреть файл

@ -403,7 +403,7 @@ class LoggerRepository {
return this._rootLogger;
}
set rootLogger(logger) {
throw "Cannot change the root logger";
throw new Error("Cannot change the root logger");
}
_updateParents(name) {

Просмотреть файл

@ -207,11 +207,11 @@ Notification.prototype = {
function PopupNotifications(tabbrowser, panel,
iconBox, options = {}) {
if (!tabbrowser)
throw "Invalid tabbrowser";
throw new Error("Invalid tabbrowser");
if (iconBox && ChromeUtils.getClassName(iconBox) != "XULElement")
throw "Invalid iconBox";
throw new Error("Invalid iconBox");
if (ChromeUtils.getClassName(panel) != "XULPopupElement")
throw "Invalid panel";
throw new Error("Invalid panel");
this._shouldSuppress = options.shouldSuppress || (() => false);
this._suppress = this._shouldSuppress();
@ -476,13 +476,13 @@ PopupNotifications.prototype = {
}
if (!browser)
throw "PopupNotifications_show: invalid browser";
throw new Error("PopupNotifications_show: invalid browser");
if (!id)
throw "PopupNotifications_show: invalid ID";
throw new Error("PopupNotifications_show: invalid ID");
if (mainAction && isInvalidAction(mainAction))
throw "PopupNotifications_show: invalid mainAction";
throw new Error("PopupNotifications_show: invalid mainAction");
if (secondaryActions && secondaryActions.some(isInvalidAction))
throw "PopupNotifications_show: invalid secondaryActions";
throw new Error("PopupNotifications_show: invalid secondaryActions");
let notification = new Notification(id, message, anchorID, mainAction,
secondaryActions, browser, this, options);
@ -552,7 +552,7 @@ PopupNotifications.prototype = {
*/
locationChange: function PopupNotifications_locationChange(aBrowser) {
if (!aBrowser)
throw "PopupNotifications_locationChange: invalid browser";
throw new Error("PopupNotifications_locationChange: invalid browser");
let notifications = this._getNotificationsForBrowser(aBrowser);
@ -1502,10 +1502,10 @@ PopupNotifications.prototype = {
}
if (!notificationEl)
throw "PopupNotifications._onButtonEvent: couldn't find notification element";
throw new Error("PopupNotifications._onButtonEvent: couldn't find notification element");
if (!notificationEl.notification)
throw "PopupNotifications._onButtonEvent: couldn't find notification";
throw new Error("PopupNotifications._onButtonEvent: couldn't find notification");
let notification = notificationEl.notification;
@ -1580,7 +1580,7 @@ PopupNotifications.prototype = {
_onMenuCommand: function PopupNotifications_onMenuCommand(event) {
let target = event.originalTarget;
if (!target.action || !target.notification)
throw "menucommand target has no associated action/notification";
throw new Error("menucommand target has no associated action/notification");
let notificationEl = getNotificationFromElement(target);
event.stopPropagation();

Просмотреть файл

@ -676,7 +676,7 @@ XMLPropertyListReader.prototype = {
case "real": {
let number = parseFloat(aDOMElt.textContent.trim());
if (isNaN(number))
throw "Could not parse float value";
throw new Error("Could not parse float value");
return number;
}
case "date":

Просмотреть файл

@ -254,7 +254,7 @@ var SimpleServiceDiscovery = {
// We must have "id", "target" and "factory" defined
if (!("id" in aDevice) || !("target" in aDevice) || !("factory" in aDevice)) {
// Fatal for registration
throw "Registration requires an id, a target and a location";
throw new Error("Registration requires an id, a target and a location");
}
// Only add if we don't already know about this device

Просмотреть файл

@ -164,7 +164,7 @@ add_task(async function test_override_super_multiple() {
* ensures that this does not block other functions from being registered.
*/
add_task(async function test_override_error() {
let errorOverrideFn = base => { throw "Expected error."; };
let errorOverrideFn = base => { throw new Error("Expected error."); };
Integration.testModule.register(errorOverrideFn);
Integration.testModule.register(overrideFn);

Просмотреть файл

@ -134,17 +134,17 @@ add_task(async function log_message_with_params() {
// Fall back to .toSource() if JSON.stringify() fails on an object.
ob = function() {};
ob.toJSON = function() {throw "oh noes JSON";};
ob.toJSON = function() {throw new Error("oh noes JSON");};
Assert.equal(formatMessage("Fail is ${sub}", {sub: ob}),
"Fail is (function() {})");
// Fall back to .toString if both .toJSON and .toSource fail.
ob.toSource = function() {throw "oh noes SOURCE";};
ob.toSource = function() {throw new Error("oh noes SOURCE");};
Assert.equal(formatMessage("Fail is ${sub}", {sub: ob}),
"Fail is function() {}");
// Fall back to '[object]' if .toJSON, .toSource and .toString fail.
ob.toString = function() {throw "oh noes STRING";};
ob.toString = function() {throw new Error("oh noes STRING");};
Assert.equal(formatMessage("Fail is ${sub}", {sub: ob}),
"Fail is [object]");
@ -208,9 +208,9 @@ add_task(async function log_message_with_params() {
// We use object.valueOf() internally; make sure a broken valueOf() method
// doesn't cause the logger to fail.
/* eslint-disable object-shorthand */
let vOf = {a: 1, valueOf: function() {throw "oh noes valueOf";}};
let vOf = {a: 1, valueOf: function() {throw new Error("oh noes valueOf");}};
Assert.equal(formatMessage("Broken valueOf ${}", vOf),
'Broken valueOf ({a:1, valueOf:(function() {throw "oh noes valueOf";})})');
'Broken valueOf ({a:1, valueOf:(function() {throw new Error("oh noes valueOf");})})');
/* eslint-enable object-shorthand */
// Test edge cases of bad data to formatter:

Просмотреть файл

@ -143,7 +143,7 @@ tests.push(
function onResolve() {
// Since this file is in strict mode, the correct value is "undefined".
Assert.equal(this, undefined);
throw "reject";
throw new Error("reject");
}
).then(
null,

Просмотреть файл

@ -68,7 +68,7 @@ function getServicePack() {
if (0 === GetVersionEx(winVer.address())) {
// Using "throw" instead of "do_throw" (see NOTE above)
throw ("Failure in GetVersionEx (returned 0)");
throw new Error("Failure in GetVersionEx (returned 0)");
}
return winVer.wServicePackMajor + "." + winVer.wServicePackMinor + "." +
@ -125,7 +125,7 @@ function getProcArchitecture() {
return "x86";
default:
// Using "throw" instead of "do_throw" (see NOTE above)
throw ("Unknown architecture returned from GetNativeSystemInfo: " + sysInfo.wProcessorArchitecture);
throw new Error("Unknown architecture returned from GetNativeSystemInfo: " + sysInfo.wProcessorArchitecture);
}
} finally {
kernel32.close();

Просмотреть файл

@ -66,7 +66,7 @@ add_task(async function() {
try {
await checkUpdates("test_bug378216_5@tests.mozilla.org",
UPDATE_FILE);
throw "Expected the update check to fail";
throw new Error("Expected the update check to fail");
} catch (e) {}
});
@ -75,7 +75,7 @@ add_task(async function() {
await checkUpdates("test_bug378216_7@tests.mozilla.org",
UPDATE_FILE);
throw "Expected the update check to fail";
throw new Error("Expected the update check to fail");
} catch (e) {}
});
@ -88,7 +88,7 @@ add_task(async function() {
await checkUpdates("test_bug378216_8@tests.mozilla.org",
"test_updatecheck.json");
throw "Expected the update check to fail";
throw new Error("Expected the update check to fail");
} catch (e) {}
let updates = await checkUpdates("test_bug378216_8@tests.mozilla.org",
@ -147,7 +147,7 @@ add_task(async function() {
await checkUpdates("test_bug378216_15@tests.mozilla.org",
UPDATE_FILE);
throw "Update check should have failed";
throw new Error("Update check should have failed");
} catch (e) {
equal(e.status, AddonManager.ERROR_PARSE_ERROR);
}

Просмотреть файл

@ -194,7 +194,7 @@ var dialog = {
elm.setAttribute("description", app.method);
} else if (!(app instanceof Ci.nsIGIOMimeApp)) {
// We support GIO application handler, but no action required there
throw "unknown handler type";
throw new Error("unknown handler type");
}
items.insertBefore(elm, this._itemChoose);

Просмотреть файл

@ -22,7 +22,7 @@ function ast(filename) {
}
if (scriptArgs.length !== 2) {
throw "usage: js js-compare-ast.js FILE1.js FILE2.js";
throw new Error("usage: js js-compare-ast.js FILE1.js FILE2.js");
}
var ast0 = ast(scriptArgs[0]);

Просмотреть файл

@ -455,7 +455,7 @@ function delayedDefaultCallback() {
if (gTest.buttonClick) {
debugDump("clicking " + gTest.buttonClick + " button");
if (gTest.extraDelayedFinishFunction) {
throw ("Tests cannot have a buttonClick and an extraDelayedFinishFunction property");
throw new Error("Tests cannot have a buttonClick and an extraDelayedFinishFunction property");
}
gDocElem.getButton(gTest.buttonClick).click();
} else if (gTest.extraDelayedFinishFunction) {