在Gnome/gjs/Gio中如何检查错误码?目录已存在时代码无响应排查
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
evariable is an Error object, not a raw error code. - The actual error code is stored in the
codeproperty 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/subdireven ifS1doesn't exist), usemake_directory_with_parents(null)instead ofmake_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

