0Pricing
WebAssembly (WASM) for High Performance Apps · 강의

WASM 경계를 넘나드는 오류 처리

wasm-bindgen을 사용하여 Rust의 결과값, 선택값 및 패닉이 JavaScript로 넘어갈 때 이를 깔끔하게 처리합니다.

WASM 경계를 넘나드는 오류 처리은(는) CoddyKit의 무료 WebAssembly (WASM) for High Performance Apps 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebAssembly (WASM) for High Performance Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Errors Need a Bridge

Rust uses Result and Option for errors; JavaScript uses exceptions and null/undefined.

wasm-bindgen bridges these two worlds so failures surface naturally on each side.

Returning Result to JS

A Rust function returning Result<T, JsValue> becomes a JS function that either returns the value or throws.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn parse(input: &str) -> Result<i32, JsValue> {
    input.parse::<i32>()
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

Catching It in JavaScript

On the JS side, an Err arrives as a thrown exception, so wrap calls in try/catch.

try {
  const n = parse('abc');
} catch (e) {
  console.error('Parse failed:', e);
}

Mapping Custom Errors

Convert your own error types into a JsValue so JS gets a useful message. The ? operator plus map_err keeps this clean.

#[wasm_bindgen]
pub fn divide(a: i32, b: i32) -> Result<i32, JsValue> {
    if b == 0 {
        return Err(JsValue::from_str('division by zero'));
    }
    Ok(a / b)
}

Returning Option

Rust's Option<T> maps to a value or undefined in JS, perfect for nullable results.

#[wasm_bindgen]
pub fn first_char(s: &str) -> Option<char> {
    s.chars().next()
}

What Happens on Panic

A Rust panic in WASM aborts the module and is hard to debug, by default you get an unhelpful 'unreachable' error.

Panics should be rare; prefer Result for expected failures.

Better Panic Messages

The console_error_panic_hook crate forwards panic messages to the browser console, making debugging far easier.

#[wasm_bindgen(start)]
pub fn main() {
    console_error_panic_hook::set_once();
}

Result vs Panic

Choose deliberately:

  • Result, expected, recoverable errors (bad input, not found)
  • Panic, programmer bugs and invariants that should never break

Never use panics for normal control flow across the boundary.

Using a Custom Error Type

For richer errors, define a struct exported to JS, so JS can read fields instead of just a string.

#[wasm_bindgen]
pub struct AppError { pub code: i32 }

#[wasm_bindgen]
impl AppError {
    #[wasm_bindgen(getter)]
    pub fn code(&self) -> i32 { self.code }
}

Propagating with ?

Inside a function returning Result<_, JsValue>, the ? operator propagates errors cleanly when types convert.

#[wasm_bindgen]
pub fn run(input: &str) -> Result<i32, JsValue> {
    let n: i32 = input.parse().map_err(|_| JsValue::from_str('bad'))?;
    Ok(n * 2)
}

Best Practices Summary

For robust error handling:

  • Return Result<T, JsValue> so errors become JS exceptions
  • Return Option for nullable values
  • Install console_error_panic_hook for debuggable panics
  • Reserve panics for true bugs, use Result for expected failures

Quick Check

How does a Rust function returning Result<T, JsValue> behave when it returns Err and is called from JavaScript?

Recap

You now handle errors cleanly across the boundary:

  • Result becomes a JS throw; Option becomes value-or-undefined
  • Map custom errors into JsValue
  • Use console_error_panic_hook to debug panics
  • Prefer Result over panic for expected failures

Clear error semantics make Rust+WASM libraries pleasant and safe to consume from JS.

자주 묻는 질문

“WASM 경계를 넘나드는 오류 처리” 강의는 무료인가요?

네 — “WASM 경계를 넘나드는 오류 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebAssembly (WASM) for High Performance Apps 강의 전체를 잠금 해제할 수 있습니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“WASM 경계를 넘나드는 오류 처리”에서 뭘 배우나요?

wasm-bindgen을 사용하여 Rust의 결과값, 선택값 및 패닉이 JavaScript로 넘어갈 때 이를 깔끔하게 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 WebAssembly (WASM) for High Performance Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebAssembly (WASM) for High Performance Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebAssembly (WASM) for High Performance Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“WASM 경계를 넘나드는 오류 처리” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebAssembly (WASM) for High Performance Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebAssembly (WASM) for High Performance Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WebAssembly용 Rust 설정
  2. WASM용 Rust 함수 작성
  3. `wasm-bindgen`으로 효율적인 JS 상호 운용
  4. WASM 경계를 넘나드는 오류 처리
← WebAssembly (WASM) for High Performance Apps(으)로 돌아가기