You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Gnome/gjs/Gio中如何检查错误码?目录已存在时代码无响应排查

Handling Gio Error Codes in GJS & Fixing Your Directory Creation Issue

Hey there! Let's break down why your current code isn't responding when the directory already exists, and how to properly check Gio error codes in GJS.

What's Wrong with Your Current Code?

Your code attempts to catch an error when the directory exists, but the comparison e == Gio.IOErrorEnum.EXISTS won't work as expected. Here's why:

  • When you catch an error from Gio methods in GJS, the e variable is an Error object, not a raw error code.
  • The actual error code is stored in the code property of this object, and the error domain (like IO errors) is represented via a quark.

So your condition never evaluates to true, which is why you see no output when the directory exists.

Correct Ways to Check Gio Error Codes

There are two reliable ways to check for specific Gio errors in GJS:

1. Check the code Property

Since Gio.IOErrorEnum.EXISTS maps directly to the numeric error code stored in e.code, you can compare those values:

let s_dir = Gio.file_new_for_path("./S1");
try {
  s_dir.make_directory(null);
  print("Directory created successfully!");
} catch (e) {
  if (e.code === Gio.IOErrorEnum.EXISTS) {
    print("Error: The directory already exists!");
  } else {
    print(`Unexpected error occurred: ${e.message} (Error code: ${e.code})`);
  }
}

2. Use e.matches() (More Rigorous)

For full accuracy (since different error domains can have identical numeric codes), use the matches() method on the error object. You'll need to pass the error domain's quark (via Gio.io_error_quark()) and the specific error code:

let s_dir = Gio.file_new_for_path("./S1");
try {
  s_dir.make_directory(null);
  print("Directory created successfully!");
} catch (e) {
  if (e.matches(Gio.io_error_quark(), Gio.IOErrorEnum.EXISTS)) {
    print("Error: The directory already exists!");
  } else {
    print(`Unexpected error: ${e.message}`);
  }
}

Bonus Tips

  • If you need to create nested directories (e.g., ./S1/subdir even if S1 doesn't exist), use make_directory_with_parents(null) instead of make_directory(null).
  • Always handle unexpected errors too—don't just check for EXISTS! Permissions issues, invalid paths, or filesystem errors can all throw other IO errors.

内容的提问来源于stack exchange,提问作者eiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:58:49