How to catch a returned Err in VS Code?

I'm using VS Code to debug my code. In debug mode, it catches panics and shows the whole error stack. But if it was an Err variant that bubbled and caused the program to halt, I can't see anything, just the printed error.

My error type is custom one, with no payload, created with a simple macro:

#[macro_export]
macro_rules! error_struct {
	($name:ident) => {
		#[derive(Debug, Clone)]
		pub struct $name;
		impl std::error::Error for $name {}
		impl std::fmt::Display for $name {
			fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				write!(f, "{}", stringify!($name))
			}
		}
	}
}

Usage:

error_struct!(MyErrorStruct);
...
if some_condition { return Err(MyErrorStruct); }

I'm not even seeing where it happens. (I may browse the code and find the place, but wish I could just see this in debugger.)

What are the options? Collect stack trace info when the struct is created? (point me please at the crate to use, please)

I came up with compulsory ::new and panicking in it in debug mode:

#[macro_export]
macro_rules! error_struct {
	($name:ident) => {
		#[derive(Debug, Clone)]
		pub struct $name {_blocker: u32}
		impl $name {
			pub fn new() -> Self {
				if cfg!(debug_assertions) {
					panic!()
				}
				Self { _blocker: 0 }
			}
		}
		impl std::error::Error for $name {}
		impl std::fmt::Display for $name {
			fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				write!(f, "{}", stringify!($name))
			}
		}
	}
}

So that ::new() were required, and it would panic in debug mode, exposing me the stack trace.

error_struct!(MyErrorStruct);
...
if some_condition { return Err(MyErrorStruct::new()) }

Please tell if there's a better way.

You shouldn't need to add a panic. If you have a MyErrorStruct::new() function, you should be able to add a breakpoint to it and VS Code will pause the debugger whenever MyErrorStruct is created.

That might not be compatible with your error_struct!() macro though because you won't have a particular line of code that can be debugged.

1 Like

anyhow - Rust with features = ["backtrace"]

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.