Merge pull request #16544 from Snuffleupagus/eslint-prefer-optional-catch-binding

Enable the `unicorn/prefer-optional-catch-binding` ESLint plugin rule
This commit is contained in:
Jonas Jenwald 2023-06-15 12:25:42 +02:00 committed by GitHub
commit 033228a2fc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 45 additions and 44 deletions

View File

@ -72,6 +72,7 @@
"unicorn/prefer-logical-operator-over-ternary": "error", "unicorn/prefer-logical-operator-over-ternary": "error",
"unicorn/prefer-modern-dom-apis": "error", "unicorn/prefer-modern-dom-apis": "error",
"unicorn/prefer-negative-index": "error", "unicorn/prefer-negative-index": "error",
"unicorn/prefer-optional-catch-binding": "error",
"unicorn/prefer-regexp-test": "error", "unicorn/prefer-regexp-test": "error",
"unicorn/prefer-string-replace-all": "error", "unicorn/prefer-string-replace-all": "error",
"unicorn/prefer-string-starts-ends-with": "error", "unicorn/prefer-string-starts-ends-with": "error",

View File

@ -174,7 +174,7 @@ const PDFViewerApplication = {
let title = pdfjsLib.getFilenameFromUrl(url) || url; let title = pdfjsLib.getFilenameFromUrl(url) || url;
try { try {
title = decodeURIComponent(title); title = decodeURIComponent(title);
} catch (e) { } catch {
// decodeURIComponent may throw URIError, // decodeURIComponent may throw URIError,
// fall back to using the unprocessed url in that case // fall back to using the unprocessed url in that case
} }

View File

@ -62,7 +62,7 @@ var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders']
} }
try { try {
registerListener(["requestHeaders", "extraHeaders"]); registerListener(["requestHeaders", "extraHeaders"]);
} catch (e) { } catch {
// "extraHeaders" is not supported in Chrome 71 and earlier. // "extraHeaders" is not supported in Chrome 71 and earlier.
registerListener(["requestHeaders"]); registerListener(["requestHeaders"]);
} }

View File

@ -66,7 +66,7 @@
if (element.dataset.l10nArgs) { if (element.dataset.l10nArgs) {
try { try {
args = JSON.parse(element.dataset.l10nArgs); args = JSON.parse(element.dataset.l10nArgs);
} catch (e) { } catch {
console.warn("[l10n] could not parse arguments for #" + key + ""); console.warn("[l10n] could not parse arguments for #" + key + "");
} }
} }

View File

@ -594,7 +594,7 @@ function checkFile(filePath) {
try { try {
const stat = fs.lstatSync(filePath); const stat = fs.lstatSync(filePath);
return stat.isFile(); return stat.isFile();
} catch (e) { } catch {
return false; return false;
} }
} }
@ -603,7 +603,7 @@ function checkDir(dirPath) {
try { try {
const stat = fs.lstatSync(dirPath); const stat = fs.lstatSync(dirPath);
return stat.isDirectory(); return stat.isDirectory();
} catch (e) { } catch {
return false; return false;
} }
} }

View File

@ -28,7 +28,7 @@ class CFFFont {
this.seacs = this.cff.seacs; this.seacs = this.cff.seacs;
try { try {
this.data = compiler.compile(); this.data = compiler.compile();
} catch (e) { } catch {
warn("Failed to compile font " + properties.loadedName); warn("Failed to compile font " + properties.loadedName);
// There may have just been an issue with the compiler, set the data // There may have just been an issue with the compiler, set the data
// anyway and hope the font loaded. // anyway and hope the font loaded.

View File

@ -1734,7 +1734,7 @@ const CipherTransformFactory = (function CipherTransformFactoryClosure() {
if (revision === 6) { if (revision === 6) {
try { try {
password = utf8StringToString(password); password = utf8StringToString(password);
} catch (ex) { } catch {
warn( warn(
"CipherTransformFactory: Unable to convert UTF8 encoded password." "CipherTransformFactory: Unable to convert UTF8 encoded password."
); );

View File

@ -53,7 +53,7 @@ class DatasetReader {
const parser = new DatasetXMLParser({ hasAttributes: true }); const parser = new DatasetXMLParser({ hasAttributes: true });
try { try {
parser.parseFromString(data["xdp:xdp"]); parser.parseFromString(data["xdp:xdp"]);
} catch (_) {} } catch {}
this.node = parser.node; this.node = parser.node;
} }
} }

View File

@ -1057,7 +1057,7 @@ class PDFDocument {
const str = stringToUTF8String(stream.getString()); const str = stringToUTF8String(stream.getString());
const data = { [key]: str }; const data = { [key]: str };
return shadow(this, "xfaDatasets", new DatasetReader(data)); return shadow(this, "xfaDatasets", new DatasetReader(data));
} catch (_) { } catch {
warn("XFA - Invalid utf-8 string."); warn("XFA - Invalid utf-8 string.");
break; break;
} }
@ -1077,7 +1077,7 @@ class PDFDocument {
} }
try { try {
data[key] = stringToUTF8String(stream.getString()); data[key] = stringToUTF8String(stream.getString());
} catch (_) { } catch {
warn("XFA - Invalid utf-8 string."); warn("XFA - Invalid utf-8 string.");
return null; return null;
} }

View File

@ -1498,7 +1498,7 @@ class PartialEvaluator {
); );
operatorList.addOp(fn, tilingPatternIR); operatorList.addOp(fn, tilingPatternIR);
return undefined; return undefined;
} catch (ex) { } catch {
// Handle any errors during normal TilingPattern parsing. // Handle any errors during normal TilingPattern parsing.
} }
} }

View File

@ -3045,7 +3045,7 @@ class Font {
cff.duplicateFirstGlyph(); cff.duplicateFirstGlyph();
const compiler = new CFFCompiler(cff); const compiler = new CFFCompiler(cff);
tables["CFF "].data = compiler.compile(); tables["CFF "].data = compiler.compile();
} catch (e) { } catch {
warn("Failed to compile font " + properties.loadedName); warn("Failed to compile font " + properties.loadedName);
} }
} }

View File

@ -129,7 +129,7 @@ class ImageResizer {
const opacity = ctx.getImageData(0, 0, 1, 1).data[3]; const opacity = ctx.getImageData(0, 0, 1, 1).data[3];
canvas.width = canvas.height = 1; canvas.width = canvas.height = 1;
return opacity !== 0; return opacity !== 0;
} catch (e) { } catch {
return false; return false;
} }
} }

View File

@ -67,7 +67,7 @@ function getHeaderBlock(stream, suggestedLength) {
try { try {
headerBytes = stream.getBytes(suggestedLength); headerBytes = stream.getBytes(suggestedLength);
headerBytesLength = headerBytes.length; headerBytesLength = headerBytes.length;
} catch (ex) { } catch {
// Ignore errors if the `suggestedLength` is huge enough that a Uint8Array // Ignore errors if the `suggestedLength` is huge enough that a Uint8Array
// cannot hold the result of `getBytes`, and fallback to simply checking // cannot hold the result of `getBytes`, and fallback to simply checking
// the entire stream (fixes issue3928.pdf). // the entire stream (fixes issue3928.pdf).

View File

@ -644,7 +644,7 @@ class XFAObject {
for (const $symbol of Object.getOwnPropertySymbols(this)) { for (const $symbol of Object.getOwnPropertySymbols(this)) {
try { try {
clone[$symbol] = this[$symbol]; clone[$symbol] = this[$symbol];
} catch (_) { } catch {
shadow(clone, $symbol, this[$symbol]); shadow(clone, $symbol, this[$symbol]);
} }
} }

View File

@ -523,7 +523,7 @@ function getUrlProp(val) {
try { try {
// The full path is required in the 'url' field. // The full path is required in the 'url' field.
return new URL(val, window.location).href; return new URL(val, window.location).href;
} catch (ex) { } catch {
if ( if (
typeof PDFJSDev !== "undefined" && typeof PDFJSDev !== "undefined" &&
PDFJSDev.test("GENERIC") && PDFJSDev.test("GENERIC") &&
@ -2011,7 +2011,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
if (!base.origin || base.origin === "null") { if (!base.origin || base.origin === "null") {
return false; // non-HTTP url return false; // non-HTTP url
} }
} catch (e) { } catch {
return false; return false;
} }
@ -2187,7 +2187,7 @@ class PDFWorker {
} }
try { try {
sendTest(); sendTest();
} catch (e) { } catch {
// We need fallback to a faked worker. // We need fallback to a faked worker.
this._setupFakeWorker(); this._setupFakeWorker();
} }
@ -2204,7 +2204,7 @@ class PDFWorker {
// The worker shall process only the first received "test" message. // The worker shall process only the first received "test" message.
sendTest(); sendTest();
return; return;
} catch (e) { } catch {
info("The worker has been disabled."); info("The worker has been disabled.");
} }
} }
@ -2305,7 +2305,7 @@ class PDFWorker {
static get _mainThreadWorkerMessageHandler() { static get _mainThreadWorkerMessageHandler() {
try { try {
return globalThis.pdfjsWorker?.WorkerMessageHandler || null; return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
} catch (ex) { } catch {
return null; return null;
} }
} }

View File

@ -89,7 +89,7 @@ function getFilenameFromContentDispositionHeader(contentDisposition) {
const buffer = stringToBytes(value); const buffer = stringToBytes(value);
value = decoder.decode(buffer); value = decoder.decode(buffer);
needsEncodingFixup = false; needsEncodingFixup = false;
} catch (e) { } catch {
// TextDecoder constructor threw - unrecognized encoding. // TextDecoder constructor threw - unrecognized encoding.
} }
} }
@ -207,7 +207,7 @@ function getFilenameFromContentDispositionHeader(contentDisposition) {
} // else encoding is b or B - base64 (RFC 2047 section 4.1) } // else encoding is b or B - base64 (RFC 2047 section 4.1)
try { try {
text = atob(text); text = atob(text);
} catch (e) {} } catch {}
return textdecode(charset, text); return textdecode(charset, text);
} }
); );

View File

@ -648,7 +648,7 @@ function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
suggestedFilename = reFilename.exec( suggestedFilename = reFilename.exec(
decodeURIComponent(suggestedFilename) decodeURIComponent(suggestedFilename)
)[0]; )[0];
} catch (ex) { } catch {
// Possible (extremely rare) errors: // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf" // URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf" // TypeError "null has no properties", e.g. for "%2F.pdf"
@ -702,7 +702,7 @@ function isValidFetchUrl(url, baseUrl) {
const { protocol } = baseUrl ? new URL(url, baseUrl) : new URL(url); const { protocol } = baseUrl ? new URL(url, baseUrl) : new URL(url);
// The Fetch API only supports the http/https protocols, and not file/ftp. // The Fetch API only supports the http/https protocols, and not file/ftp.
return protocol === "http:" || protocol === "https:"; return protocol === "http:" || protocol === "https:";
} catch (ex) { } catch {
return false; // `new URL()` will throw on incorrect data. return false; // `new URL()` will throw on incorrect data.
} }
} }

View File

@ -74,7 +74,7 @@ function extractFilenameFromHeader(getResponseHeader) {
if (filename.includes("%")) { if (filename.includes("%")) {
try { try {
filename = decodeURIComponent(filename); filename = decodeURIComponent(filename);
} catch (ex) {} } catch {}
} }
if (isPdfFile(filename)) { if (isPdfFile(filename)) {
return filename; return filename;

View File

@ -144,7 +144,7 @@ class AForm {
let date = null; let date = null;
try { try {
date = this._util.scand(cFormat, cDate); date = this._util.scand(cFormat, cDate);
} catch (error) {} } catch {}
if (!date) { if (!date) {
date = Date.parse(cDate); date = Date.parse(cDate);
if (isNaN(date)) { if (isNaN(date)) {

View File

@ -434,7 +434,7 @@ function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
if (options.tryConvertEncoding) { if (options.tryConvertEncoding) {
try { try {
url = stringToUTF8String(url); url = stringToUTF8String(url);
} catch (ex) {} } catch {}
} }
} }
@ -442,7 +442,7 @@ function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
if (_isValidProtocol(absoluteUrl)) { if (_isValidProtocol(absoluteUrl)) {
return absoluteUrl; return absoluteUrl;
} }
} catch (ex) { } catch {
/* `new URL()` will throw on incorrect data. */ /* `new URL()` will throw on incorrect data. */
} }
return null; return null;
@ -605,7 +605,7 @@ function isEvalSupported() {
try { try {
new Function(""); // eslint-disable-line no-new, no-new-func new Function(""); // eslint-disable-line no-new, no-new-func
return true; return true;
} catch (e) { } catch {
return false; return false;
} }
} }

View File

@ -471,7 +471,7 @@ describe("Interaction", () => {
await page._client.send("Page.setDownloadBehavior", { await page._client.send("Page.setDownloadBehavior", {
behavior: "deny", behavior: "deny",
}); });
} catch (_) {} } catch {}
await clearInput(page, getSelector("47R")); await clearInput(page, getSelector("47R"));
await page.evaluate(_ => { await page.evaluate(_ => {
window.document.activeElement.blur(); window.document.activeElement.blur();

View File

@ -168,7 +168,7 @@ describe("api", function () {
// Shouldn't get here. // Shouldn't get here.
expect(false).toEqual(true); expect(false).toEqual(true);
} catch (reason) { } catch {
expect(true).toEqual(true); expect(true).toEqual(true);
await destroyed; await destroyed;
} }

View File

@ -549,7 +549,7 @@ describe("CipherTransformFactory", function () {
try { try {
const factory = new CipherTransformFactory(dict, fileId, password); const factory = new CipherTransformFactory(dict, fileId, password);
expect("createCipherTransform" in factory).toEqual(true); expect("createCipherTransform" in factory).toEqual(true);
} catch (ex) { } catch {
// Shouldn't get here. // Shouldn't get here.
expect(false).toEqual(true); expect(false).toEqual(true);
} }

View File

@ -368,7 +368,7 @@ describe("evaluator", function () {
// Shouldn't get here. // Shouldn't get here.
expect(false).toEqual(true); expect(false).toEqual(true);
} catch (_) { } catch {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(0); expect(result.fnArray.length).toEqual(0);
} }
@ -389,7 +389,7 @@ describe("evaluator", function () {
// Shouldn't get here. // Shouldn't get here.
expect(false).toEqual(true); expect(false).toEqual(true);
} catch (_) { } catch {
expect(true).toEqual(true); expect(true).toEqual(true);
} }
}); });

View File

@ -90,7 +90,7 @@ WebServer.prototype = {
// Windows paths cause issues in statFile and serverDirectoryIndex. // Windows paths cause issues in statFile and serverDirectoryIndex.
// Converting to unix path would avoid platform checks in said functions. // Converting to unix path would avoid platform checks in said functions.
pathPart = pathPart.replaceAll("\\", "/"); pathPart = pathPart.replaceAll("\\", "/");
} catch (ex) { } catch {
// If the URI cannot be decoded, a `URIError` is thrown. This happens for // If the URI cannot be decoded, a `URIError` is thrown. This happens for
// malformed URIs such as `http://localhost:8888/%s%s` and should be // malformed URIs such as `http://localhost:8888/%s%s` and should be
// handled as a bad request. // handled as a bad request.

View File

@ -815,7 +815,7 @@ const PDFViewerApplication = {
if (!title) { if (!title) {
try { try {
title = decodeURIComponent(getFilenameFromUrl(url)) || url; title = decodeURIComponent(getFilenameFromUrl(url)) || url;
} catch (ex) { } catch {
// decodeURIComponent may throw URIError, // decodeURIComponent may throw URIError,
// fall back to using the unprocessed url in that case // fall back to using the unprocessed url in that case
title = url; title = url;
@ -876,7 +876,7 @@ const PDFViewerApplication = {
try { try {
// Trigger saving, to prevent data loss in forms; see issue 12257. // Trigger saving, to prevent data loss in forms; see issue 12257.
await this.save(); await this.save();
} catch (reason) { } catch {
// Ignoring errors, to ensure that document closing won't break. // Ignoring errors, to ensure that document closing won't break.
} }
} }
@ -1044,7 +1044,7 @@ const PDFViewerApplication = {
const blob = new Blob([data], { type: "application/pdf" }); const blob = new Blob([data], { type: "application/pdf" });
await this.downloadManager.download(blob, url, filename, options); await this.downloadManager.download(blob, url, filename, options);
} catch (reason) { } catch {
// When the PDF document isn't ready, or the PDF file is still // When the PDF document isn't ready, or the PDF file is still
// downloading, simply download using the URL. // downloading, simply download using the URL.
await this.downloadManager.downloadUrl(url, filename, options); await this.downloadManager.downloadUrl(url, filename, options);

View File

@ -150,7 +150,7 @@ function isRuntimeAvailable() {
if (chrome.runtime?.getManifest()) { if (chrome.runtime?.getManifest()) {
return true; return true;
} }
} catch (e) {} } catch {}
return false; return false;
} }

View File

@ -106,7 +106,7 @@ class GrabToPan {
try { try {
// eslint-disable-next-line no-unused-expressions // eslint-disable-next-line no-unused-expressions
event.originalTarget.tagName; event.originalTarget.tagName;
} catch (e) { } catch {
// Mozilla-specific: element is a scrollbar (XUL element) // Mozilla-specific: element is a scrollbar (XUL element)
return; return;
} }

View File

@ -445,7 +445,7 @@ class PDFLinkService {
// e.g. "4.3" or "true", because `JSON.parse` converted its type. // e.g. "4.3" or "true", because `JSON.parse` converted its type.
dest = dest.toString(); dest = dest.toString();
} }
} catch (ex) {} } catch {}
if ( if (
typeof dest === "string" || typeof dest === "string" ||

View File

@ -341,7 +341,7 @@ class PDFOutlineViewer extends BaseTreeViewer {
return null; // The document was closed while the data resolved. return null; // The document was closed while the data resolved.
} }
this.linkService.cachePageRef(pageNumber, destRef); this.linkService.cachePageRef(pageNumber, destRef);
} catch (ex) { } catch {
// Invalid page reference, ignore it and continue parsing. // Invalid page reference, ignore it and continue parsing.
} }
} }

View File

@ -101,7 +101,7 @@ class PDFPresentationMode {
await promise; await promise;
pdfViewer.focus(); // Fixes bug 1787456. pdfViewer.focus(); // Fixes bug 1787456.
return true; return true;
} catch (reason) { } catch {
this.#removeFullscreenChangeListeners(); this.#removeFullscreenChangeListeners();
this.#notifyStateChange(PresentationModeState.NORMAL); this.#notifyStateChange(PresentationModeState.NORMAL);
} }

View File

@ -487,7 +487,7 @@ class PDFScriptingManager {
try { try {
await this._scripting.destroySandbox(); await this._scripting.destroySandbox();
} catch (ex) {} } catch {}
for (const [name, listener] of this._internalEvents) { for (const [name, listener] of this._internalEvents) {
this._eventBus._off(name, listener); this._eventBus._off(name, listener);