From 6d8b0294d6c8b06f3accd05092104997c22820d4 Mon Sep 17 00:00:00 2001 From: numzero Date: Tue, 11 Nov 2025 01:01:21 +0300 Subject: [PATCH] Rusty error handling --- src/main.rs | 43 +++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/src/main.rs b/src/main.rs index a886807..e4ea263 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,22 +19,20 @@ struct MainWindow { } impl MainWindow { - fn new(event_loop: &ActiveEventLoop) -> Self { - let handle = event_loop - .create_window(Window::default_attributes().with_title(TITLE)) - .unwrap(); + fn new(event_loop: &ActiveEventLoop) -> Result> { + let handle = event_loop.create_window(Window::default_attributes().with_title(TITLE))?; let handle = Arc::new(handle); - let (device, queue, surface) = pollster::block_on(init_gpu(Arc::clone(&handle))).unwrap(); + let (device, queue, surface) = pollster::block_on(init_gpu(Arc::clone(&handle)))?; queue.submit([]); - Self { + Ok(Self { handle, device, queue, surface, surface_configured: false, - } + }) } fn render(&self, output: &wgpu::Texture) { @@ -88,7 +86,13 @@ impl MainWindow { if !self.surface_configured { return; } - let output = self.surface.get_current_texture().unwrap(); + let output = match self.surface.get_current_texture() { + Ok(texture) => texture, + Err(err) => { + eprintln!("error: can't redraw: can't get target texture: {err:#}"); + return; + } + }; self.render(&output.texture); output.present(); } @@ -109,7 +113,15 @@ impl Application { impl ApplicationHandler for Application { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - self.main_window = Some(MainWindow::new(event_loop)); + let main_window = match MainWindow::new(event_loop) { + Ok(window) => window, + Err(err) => { + eprintln!("error: can't resume: can't create the main window: {err:#}"); + event_loop.exit(); + return; + } + }; + self.main_window = Some(main_window); } fn window_event( @@ -141,18 +153,17 @@ async fn init_gpu<'window>( compatible_surface: Some(&surface), force_fallback_adapter: false, }) - .await - .unwrap(); + .await?; let (device, queue) = adapter .request_device(&wgpu::DeviceDescriptor::default()) - .await - .unwrap(); + .await?; Ok((device, queue, surface)) } -fn main() { - let event_loop = EventLoop::new().unwrap(); +fn main() -> Result<(), Box> { + let event_loop = EventLoop::new()?; event_loop.set_control_flow(ControlFlow::Wait); let mut app = Application::new(); - event_loop.run_app(&mut app).unwrap(); + event_loop.run_app(&mut app)?; + Ok(()) }