如何跟踪错误结果的原因? [英] How to trace the cause of an error result?

查看:83
本文介绍了如何跟踪错误结果的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写使用 Result 类型的代码时,您可能希望用户和开发人员使用不同的行为。

When writing code that uses Result type, you may want different behavior for users and developers.


  • 在编写可以妥善处理错误的应用程序时,最好使用 Result

  • 在开发过程中可能需要可以捕获错误,以查看由哪一行代码创建错误,或者在创建 Err 值后获取堆栈跟踪。

  • When writing an application that gracefully handles errors, it's nice to use Result.
  • During development you may want to "catch" the error to see what line of code creates the error or get a stack-trace the moment the Err value is created.

如果您犯了一个独特的错误,搜索起来并不难,但是如果该错误来自标准库,则该错误可能非常笼统。

If you make a unique error it's not hard to search for it, but if the error is from the standard library, the error may be very generic.

例如,如果不手动更改每个<$ c $,就不可能知道哪个 read 命令导致了意外的文件结尾。 c> file.read()?到 file.read()。unwrap()

For example, it's impossible to know which read command caused an unexpected end-of-file without manually changing every file.read()? to file.read().unwrap().

是否有一种方便的方法来从 Result 获得堆栈跟踪?

Is there a convenient way to get a stack-trace from a Result?

可行的解决方案可能是创建一个读取宏, read_in_r elease_unwrap_in_debug!(文件,数据) ...但是感觉很尴尬。

A weak but workable solution could be to make a macro for reading, read_in_release_unwrap_in_debug!(file, data)... but this feels very awkward.

I有一个文件读取器,其中有许多 read 调用,但其中一个失败。我不确定哪个。在运行时,我想将结果推回给调用者。对于调试,我希望停止失败的读取调用,或者以某种方式让我知道它的行号。

I have a file reader with many read calls and one fails. I'm not sure which. At run-time, I want to push the result back to the caller. For debugging, I want the failed read call to stop or somehow let me know its line number.

推荐答案

结果本身不会没有任何回溯信息,但是您可以将其添加到自定义错误类型。

A result by itself doesn't have any backtrace information, but you can add it to custom error types.

错误链条板箱是为您生成错误类型的示例,当 RUST_BACKTRACE 时,您可以免费获得错误类型设置了环境变量。

The error_chain crate is an example which generates an error type for you, for which you get backtrace generation for free when the RUST_BACKTRACE environment variable is set.

您还可以使用 backtrace 库,然后自己完成。

You could also use the backtrace library directly and do it yourself.

这篇关于如何跟踪错误结果的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆