---
title: wgpu Error Handling
lang: en-GB
author: Maggie Harley
date: 08/04/2025
---

When using the Rust `wgpu` crate, I like to collect WebGPU errors into a list,
so that I can process them inside the event loop. I collect them like so:

```rust
fn create_error_list(device: &Device) -> Arc<Mutex<wgpu::Error>> {
    let result = Arc::new(Mutex::new(vec![]));
    let clone = result.clone();
    let handler = move |error| {
        if let Ok(mut errors) = clone.lock() {
            errors.push(error);
        }
    };
    device.on_uncaptured_error(Box::new(handler));
    result
}
```

`create_error_list` returns an arc clone containing an error list (wrapped by a
mutex). This list is populated with `wgpu` errors as they occur. Reading the
list requires locking the mutex. The idea is that `create_error_list` is run at
application initialisation, and the error list checked on every iteration of
the event loop.

This code took me a while to come to, so it might be valuable to someone else.
I designed it while attempting to remove all panicking from my code, and as a
result there are no `.unwrap`s left.

The contents of the handler might look strange: we only do something if the
mutex can be locked. A mutex only returns a non-`Ok` value if it has been
poisoned. Poisoned mutexes are never un-poisoned, so the mutex will still be
poisoned when the event-loop thread attempts to read the error list. Having the
event-loop thread handle the mutex error instead of a handler is a nice
seperation of concerns: an error handler for `wgpu` errors probably shouldn't
have to worry about mutex errors. Delegating mutex error handling to the
event-loop thread, which may have control of more resources than the simple
handler function defined above, allows the program to handle the error
gracefully---or, at least, not panic.
