【问题标题】:Error catching in JavaScript does not catch error properlyJavaScript 中的错误捕获不能正确捕获错误
【发布时间】:2021-07-26 22:50:01
【问题描述】:

我正在开发一个使用 p5.js 库的 javascript 游戏。我正在尝试加载我自己的字体,我在其中使用 .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...");

}

但是,每当我尝试运行我的代码时,我的画布不仅没有加载任何内容,而且错误仍然出现在控制台中。但是,我的 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

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

编辑:我尝试了另一种错误捕获方式,它由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.
  
}

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

【问题讨论】:

  • 查看错误消息,我的假设是loadFont 正在内部处理错误而不抛出异常。尝试输入 ttf 字体的绝对路径,看看是否有效。只是推测您的 javascript 文件可能是从与您想象的不同的目录运行的,因此相对路径已关闭。
  • loadFont 是一个承诺吗?
  • 我认为 loadFont 是一个承诺,但我不是 100% 确定(对不起,我还是这个概念的新手)。如果有帮助,这里是 p5 对声明的解释:p5js.org/reference/#/p5/loadFont
  • 输入绝对路径是指从“C://Users...”等开始吗?如果是这样,如果我在另一台设备上运行程序会不会有所不同?
  • loadFont 接受另外两个参数,一个成功回调和一个错误回调。您需要使用第二个来捕获错误。它记录在您提供的文档链接中。

标签: javascript error-handling assets p5.js


【解决方案1】:

正如documentation 所说:

preload() 之外,您可以提供一个回调函数来处理 对象:

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

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
}

【讨论】:

  • 我试过了,错误仍然存​​在。可能是 loadFont() 过程出错,还是在我的代码中出错?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2022-12-21
  • 2022-01-18
  • 2023-04-07
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多