การจัดการข้อผิดพลาดและข้อยกเว้น
เรียนรู้กลยุทธ์ที่รัดกุมในการส่งต่อและจัดการข้อผิดพลาดกับข้อยกเว้นระหว่างโค้ด WASM และ JavaScript อย่างมีประสิทธิภาพ
การจัดการข้อผิดพลาดและข้อยกเว้น เป็นบทเรียน WebAssembly (WASM) for High Performance Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebAssembly (WASM) for High Performance Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebAssembly (WASM) for High Performance Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Error Handling Matters
When your WebAssembly (WASM) module interacts with JavaScript, things can go wrong. Maybe a calculation fails, an input is invalid, or a browser API call doesn't work as expected.
Proper error handling ensures your application remains stable and provides meaningful feedback to users or developers. It's about gracefully managing unexpected situations across language boundaries.
Errors in WASM Host Languages
WebAssembly itself doesn't have a concept of "exceptions" like JavaScript or Java. Instead, languages compiled to WASM (like Rust or C++) often use return types or specific data structures to signal errors.
- Rust: Employs the
Result<T, E>enum, which can be eitherOk(T)for success orErr(E)for failure. - C/C++: Often uses return values (e.g., -1 for error) or sets global error indicators.
Our focus is on how these language-specific error patterns translate across the WASM-JavaScript boundary.
Propagating WASM Errors to JS
The goal is to make errors originating in your WASM module appear as standard JavaScript Error objects. This allows JavaScript to use its familiar try...catch mechanism.
Tools like wasm-bindgen help bridge this gap by automatically converting Rust's Result::Err variants into JavaScript exceptions. It's crucial for seamless interoperation.
Rust WASM Error Example
Here's a Rust function compiled to WASM that might return an error. Notice the Result<i32, JsValue> return type. JsValue is a generic type for anything that can cross the JS boundary.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn divide_numbers(a: i32, b: i32) -> Result<i32, JsValue> {
if b == 0 {
// Return a JavaScript error value
return Err(JsValue::from_str("Cannot divide by zero!"));
}
Ok(a / b)
}
// This is a complete Rust module (lib.rs content).
// Exported functions like divide_numbers are its entry points for JavaScript.Catching WASM Errors in JS
Once your WASM module propagates an error, JavaScript can catch it using a standard try...catch block. The error object caught will be a JavaScript Error, allowing you to inspect its message and potentially other properties.
This makes integrating WASM errors into your existing JavaScript error handling flow very straightforward and familiar.
JS Consuming WASM Errors
This JavaScript code loads our WASM module and attempts to call the divide_numbers function. Observe how the try...catch block handles the division-by-zero error from WASM.
// Assume 'wasm' is the loaded WASM module from Rust
// This is typical for 'wasm-bindgen' projects.
async function runWasmExample() {
// In a real app, this would load your .wasm and .js glue code
const wasm = { divide_numbers: (a, b) => {
if (b === 0) throw new Error("Cannot divide by zero!");
return a / b;
}};
try {
// This call will succeed
let result1 = wasm.divide_numbers(10, 2);
console.log("10 / 2 =", result1); // Output: 5
// This call will throw an error from WASM (simulated here)
let result2 = wasm.divide_numbers(10, 0);
console.log("10 / 0 =", result2); // This line won't be reached
} catch (e) {
console.error("Caught WASM error:", e.message);
// Output: Caught WASM error: Cannot divide by zero!
}
}
runWasmExample();JS Errors in WASM Callbacks
What if your WASM module calls a JavaScript function (a "callback") that then throws an error? How does WASM react?
When a JavaScript function invoked by WASM throws an error, that error is typically caught by the wasm-bindgen glue code and propagated back into the WASM side as a JsValue error. Your Rust code can then handle it using the Result type, just like errors originating in Rust.
WASM Handling JS Callback Errors
Here's a Rust function that calls a JavaScript callback. The JavaScript callback might fail, and the Rust code handles that potential error.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
// Import a JS function that might throw an error
// The `catch` attribute ensures JS errors are converted to Rust `Result::Err`
#[wasm_bindgen(catch)]
fn js_might_fail(value: i32) -> Result<i32, JsValue>;
}
#[wasm_bindgen]
pub fn call_js_and_handle_error(input: i32) -> Result<String, JsValue> {
match js_might_fail(input) {
Ok(result) => Ok(format!("JS callback succeeded: {}", result)),
Err(e) => {
// Convert JsValue error back to a string for our Rust Result
let error_msg = e.as_string().unwrap_or_else(|| "Unknown JS error".into());
Err(JsValue::from_str(&format!("JS callback failed: {}", error_msg)))
}
}
}
// This is a complete Rust module (lib.rs content).Custom Error Types for Clarity
For more specific error handling, you can define custom error types in Rust and map them to JavaScript Error types. wasm-bindgen allows you to control how your Rust errors are represented in JavaScript.
This improves clarity for JavaScript consumers, allowing them to differentiate between various error conditions originating from your WASM module.
- Define specific Rust enums for errors.
- Implement
From<YourError> for JsValueto convert them. - Use
#[wasm_bindgen(js_name = MyCustomError)]for custom JS error names.
Best Practices for Error Handling
Effective error handling is key for maintainable and robust WASM applications:
- Be Explicit: Clearly define error conditions and return types in your WASM code.
- Log Errors: Use
console.erroror a logging utility in JavaScript to record WASM errors. - Graceful Degradation: Design your application to continue functioning, even if a WASM component encounters a non-critical error.
- Test Error Paths: Ensure your error handling logic is thoroughly tested to cover all failure scenarios.
Error Propagation Check
Consider the following Rust WebAssembly function and the JavaScript code that interacts with it. What will the JavaScript console output when runExample() is called?
Rust WASM Module (lib.rs):
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn check_value(value: i32) -> Result<String, JsValue> {
if value < 0 {
Err(JsValue::from_str("Value cannot be negative!"))
} else if value == 0 {
Ok("Value is zero.".into())
} else {
Ok(format!("Value is positive: {}", value))
}
}
JavaScript Host Code:
// Assume 'wasm' is the loaded WASM module via wasm-bindgen
async function runExample() {
// For context, 'wasm' would be loaded like this:
// const wasm = await import('./my_wasm_module.js');
// For this question, assume 'wasm.check_value' behaves as defined in Rust.
const wasm = {
check_value: (val) => {
if (val < 0) throw new Error("Value cannot be negative!");
if (val === 0) return "Value is zero.";
return `Value is positive: ${val}`;
}
};
try {
console.log(wasm.check_value(5));
console.log(wasm.check_value(-1)); // This will throw
} catch (e) {
console.error("Caught error:", e.message);
}
console.log(wasm.check_value(0)); // This line is outside the try...catch
}
runExample();
Recap: Robust Error Handling
In this lesson, we explored how to handle errors and exceptions when interoperating between WebAssembly and JavaScript. We learned:
- WASM's host languages use specific patterns (like Rust's
Resulttype) for errors. wasm-bindgenautomates the propagation of WASM errors to JavaScriptErrorobjects.- JavaScript's
try...catchcan effectively handle errors thrown by WASM modules. - WASM can also handle errors from JavaScript callbacks it invokes.
Mastering error handling is crucial for building reliable and user-friendly WASM applications.
คำถามที่พบบ่อย
บทเรียน “การจัดการข้อผิดพลาดและข้อยกเว้น” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจัดการข้อผิดพลาดและข้อยกเว้น” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebAssembly (WASM) for High Performance Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebAssembly (WASM) for High Performance Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจัดการข้อผิดพลาดและข้อยกเว้น”
เรียนรู้กลยุทธ์ที่รัดกุมในการส่งต่อและจัดการข้อผิดพลาดกับข้อยกเว้นระหว่างโค้ด WASM และ JavaScript อย่างมีประสิทธิภาพ คุณปฏิบัติ WebAssembly (WASM) for High Performance Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebAssembly (WASM) for High Performance Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebAssembly (WASM) for High Performance Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การจัดการข้อผิดพลาดและข้อยกเว้น” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน WebAssembly (WASM) for High Performance Apps นี้ได้ไหม
ได้ บทเรียน WebAssembly (WASM) for High Performance Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การดำเนินการแบบอะซิงโครนัสด้วย WASM
- การเรียกกลับ JavaScript แบบกำหนดเอง
- การจัดการข้อผิดพลาดและข้อยกเว้น
- การใช้หน่วยความจำและอาร์เรย์ชนิดข้อมูลร่วมกันระหว่างขอบเขต JS/WASM