[anyhow]: How do i print only the root cause with context?

Current output:

Error: Failed to fetch router info
Caused by:
    0: error sending request for url (http://192.168.16.1/goform/get_router_info): error trying to connect: tcp connect error: Network is unreachable (os error 101)
    1: error trying to connect: tcp connect error: Network is unreachable (os error 101)
    2: tcp connect error: Network is unreachable (os error 101)

As you can see same errors are being repeated instead what i want is:

Error: Failed to fetch router info
Caused by:
    Network is unreachable (os error 101)

I believe that cannot be done with any of the built-in error display representations which you can learn about here.

You will have to implement that logic yourself by printing:

  1. The error using its default Display implementation (println!("{}", err) or using to_string())
  2. And then the last element from the chain iterator (Error::chain), if any.

I think its common in this case to move your logic from main to another function (e.g. run() -> Result<(), anyhow::Error>) and use main to execute this function and print possible errors and error chains in a way you prefer.

1 Like

This type of redundant output occurs because the involved error types are producing it. Individual messages come from Display::fmt() and the chain come from Error::source(). In order to avoid this, modify the error types' implementations so that whatever information is in their source() is not also repeated in their Display.

That won't create the minimal output you want — that can only be done by examining the errors and skipping the #0 and #1 intermediate errors — but it will fix the redundancy.

3 Likes

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.