JavaScript 中的错误捕获没有正确捕获错误

Error catching in JavaScript does not catch error properly

我正在 javascript 开发一款游戏,它使用了 p5.js 库。我正在尝试加载我自己的字体,其中我使用的是 .ttf 文件,但有时 p5.js 无法正确加载字体。在这种情况下,我尝试使用 try 和 catch 方法检查是否发生这种情况,如果发生,将我的字体切换为始终有效的默认内置字体(不是 .ttf,只是内置).这是我与该问题有关的代码:

function preload() {

  try {

    font = loadFont("assets/BebasNeue-Regular.ttf"); // Font from Google Fonts - https://fonts.google.com/specimen/Bebas+Neue#standard-styles

  } catch (error) {

    console.error("ERROR: " + error)
    console.log("Font was unable to load, using default font.");
    font = "Helvetica";

  }

  console.log("Assets preloaded...");

}

但是,每当我尝试 运行 我的代码时,我的 canvas 不仅没有加载任何东西,而且错误仍然出现在控制台中。但是,我的 console.log 声明不存在。内容如下:

Not allowed to load local resource: blob:null/a07d873c-2d5e-4653-92f4-02fd085cc6e4
p5.js:48337 
 p5.js says: It looks like there was a problem loading your font. Try checking if the file path (assets/BebasNeue-Regular.ttf) is correct, hosting the file online, or running a local server. (More info at https://github.com/processing/p5.js/wiki/Local-server)
p5.js:80410 Font could not be loaded assets/BebasNeue-Regular.ttf
(anonymous) @ p5.js:80410
assets/BebasNeue-Regular.ttf:1 Failed to load resource: net::ERR_FAILED

即使我的资产在我的文件夹中,当我尝试 运行 程序时,它也不起作用。有谁知道如何 fix/change 我的错误捕获语句?

编辑:我尝试了一种不同的错误捕获方式,它由 loadFont() procedure 中的 p5 提供。这是我的新代码:

function preload() {

  font = loadFont("assets/BebasNeue-Regular.ttf", setup, fontError); // Font from Google Fonts - https://fonts.google.com/specimen/Bebas+Neue#standard-styles

  console.log("Assets preloaded...");

}

function fontError() { console.log("Font was unable to load, using default font."); font = "Helvetica"; }

function setup() {

  // Sets up the game, irrelevant to error.
  
}

这是我的代码下载的 link 是否有帮助:https://www.mediafire.com/file/k4nm445dkxhv0i8/game.zip/file

正如 documentation 所述:

Outside of preload(), you may supply a callback function to handle the object:

您应该像这样重构您的代码:

let font;

function preload() {
  loadFont("assets/BebasNeue-Regular.ttf", result => {
    console.log("Assets preloaded...");
    font = result;
  }, error => {
    console.error("ERROR: " + error)
    console.log("Font was unable to load, using default font.");
    font = "Helvetica";
  });
}

function setup() {
  // use the font
}