├── .github
└── workflows
│ └── rust.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── examples
├── basic.rs
├── file.rs
└── json
│ ├── bad.json
│ └── good.json
└── src
├── context.rs
├── culprit.rs
├── lib.rs
├── result.rs
├── src_location.rs
└── trace.rs
/.github/workflows/rust.yml:
--------------------------------------------------------------------------------
1 | name: Rust
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | pull_request:
7 | branches: [ "main" ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v4
19 | - name: Build
20 | run: cargo build --verbose
21 | - name: Run tests
22 | run: cargo test --verbose
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Generated by Cargo
2 | # will have compiled files and executables
3 | debug/
4 | target/
5 |
6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
8 | Cargo.lock
9 |
10 | # These are backup files generated by rustfmt
11 | **/*.rs.bk
12 |
13 | # MSVC Windows builds of rustc generate these, which store debugging information
14 | *.pdb
15 |
16 | # RustRover
17 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
18 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
19 | # and can be added to the global gitignore or merged into this file. For a more nuclear
20 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
21 | #.idea/
22 |
23 | # Added by cargo
24 |
25 | /target
26 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to culprit will be documented in this file.
4 |
5 | ## [0.4.0] - 2025-03-01
6 |
7 | - Culprit derives Clone when Context derives Clone
8 |
9 | ## [0.3.0] - 2025-01-06
10 |
11 | - Rename Fingerprint to Context
12 | - Rename what used to be Context to Trace
13 | - More idiomatic naming across the board
14 | - Exported optional Result type alias
15 |
16 | ## [0.2.0] - 2025-01-01
17 |
18 | - First working release on crates.io
19 |
20 |
21 |
22 | [0.3.0]: https://github.com/carlsverre/tryiter/compare/v0.2.0...v0.3.0
23 | [0.2.0]: https://github.com/carlsverre/tryiter/compare/3c27380...v0.2.0
24 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "culprit"
3 | version = "0.4.0"
4 | edition = "2021"
5 | authors = ["Carl Sverre"]
6 | description = "A Rust error crate with the goal of identifying precisely where and in which context an error occurs."
7 | repository = "https://github.com/carlsverre/culprit"
8 | license = "MIT OR Apache-2.0"
9 | keywords = ["error", "error-handling", "result"]
10 | readme = "README.md"
11 |
12 | [dependencies]
13 | smallvec = { version = "1.14", features = ["union"] }
14 |
15 | [dev-dependencies]
16 | serde = "1.0"
17 | serde_json = "1.0"
18 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2024 Carl Sverre
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Carl Sverre
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
Culprit
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | A Rust error crate with the goal of identifying precisely where and in which context an error occurs.
15 |
16 | **Goals:**
17 | 1. Context both in the logical control flow as well as physical space in files
18 | 2. Unique public facing errors
19 | 3. Minimal error sets per function/module
20 | 4. Aligning errors to error codes for external handling (i.e. outside of rust)
21 |
22 | > [!WARNING]
23 | > Culprit is extremely-alpha and may dramatically change at any point. It's currently undergoing design and testing within some projects. Ideas and discussion is welcome during this process.
24 |
25 | **Table of Contents**:
26 | - [Getting started](#getting-started)
27 | - [Concept and comparison to other crates](#concept-and-comparison-to-other-crates)
28 | - [Outstanding Work](#outstanding-work)
29 |
30 | # Getting started
31 |
32 | **First**, define some context types which must implement Debug and Display. A Context represents the unique error cases that can occur in your app. Context types may wrap context from other abstraction layers such as modules or crates. Context types should be small and represent the most relevant context of a given error state.
33 |
34 | ```rust
35 | #[derive(Debug)]
36 | enum StorageCtx {
37 | Io(std::io::ErrorKind),
38 | Corrupt,
39 | }
40 | impl Display for StorageCtx { ... }
41 |
42 | #[derive(Debug)]
43 | enum CalcCtx {
44 | NotANumber,
45 | Storage(StorageCtx
46 | ),
47 | }
48 | impl Display for CalcCtx { ... }
49 | ```
50 |
51 | **Next**, Implement `From` conversions to build `Contexts` from `Errors` and other `Contexts`:
52 |
53 | ```rust
54 | impl From for StorageCtx {
55 | fn from(e: std::io::Error) -> Self {
56 | StorageCtx::Io(e.kind())
57 | }
58 | }
59 |
60 | impl From for CalcCtx {
61 | fn from(f: StorageCtx) -> Self {
62 | CalcCtx::Storage(f)
63 | }
64 | }
65 | ```
66 |
67 | **Next**, use `Culprit` as the error type in a Result:
68 |
69 | ```rust
70 | fn read_file(file: &str) -> Result> {
71 | Ok(std::fs::read_to_string(file)?)
72 | }
73 |
74 | fn sum_file(file: &str) -> Result> {
75 | // calling `or_ctx` or `or_into_ctx` is required when the result already contains a Culprit but you want to change the context.
76 | let data = read_file(&req.file).or_into_ctx()?;
77 | ...
78 | }
79 | ```
80 |
81 | **Finally**, check out your fancy new Culprit error message when you debug or display a Culprit:
82 |
83 | ```
84 | Error: Calc(NotANumber)
85 | 0: not a number, at examples/file.rs:136:37
86 | 1: expected number; got String("hello"), at examples/file.rs:100:32
87 | ```
88 |
89 | > [!NOTE]
90 | > For the full example please visit [file.rs](./examples/file.rs)
91 |
92 | # Concept and comparison to other crates
93 |
94 | Culprit came around while I was exploring various error handling patterns and crates in Rust. I roughly categorize them in the following way:
95 |
96 | 1. New Type: A new type per abstraction boundary (often an enum) often wraps the source error from lower layers directly, providing additional context via the type's `Display/Debug impl` and associated fields. Example: [thiserror]
97 |
98 | 2. Accumulator: A single type that consumes an error and then allows additional context to be attached to it as it flows up the stack. Example: [anyhow]
99 |
100 | 3. Hybrid: An Accumulator type which is generic, allowing it to be specialized with a New Type (often an enum). Provides context via the New Type as well as dynamic attachments. Example: [culprit]
101 |
102 | Each of these patterns are able to capture errors as well as the **logical trace** of an erroneous program state.
103 |
104 |
105 | > [!TIP]
106 | > I define **logical trace** as the path the error takes through a program. The path is made up of steps, which primarily correlate with an error passing between modules, crates, threads, or async tasks. The developer may add context to points on the path to further illuminate the error's path. It's important to note that while they share similar properties, a logical trace is not the same as a backtrace. The former captures the error's flow through the codebase while the latter captures the state of the stack at a particular point in time.
107 |
108 | Here is a table comparing common Rust error crates to Culprit. _Please file an issue if I made a mistake or am missing a commonly used crate._
109 |
110 |
111 | | crate | pattern | uses unsafe | logical trace | captured context |
112 | | --------------- | ----------- | ----------- | ------------------------------- | --------------------------------------------------------------- |
113 | | [anyhow] | Accumulator | yes | context | strings, Backtrace³, custom types¹, source error¹ |
114 | | [error-stack] | Hybrid | yes | context, enriched, [SpanTrace]³ | strings, Backtrace³, [SpanTrace]³, custom types¹, source error¹ |
115 | | [eyre] | Accumulator | yes | context, [SpanTrace]³ | strings, Backtrace³, [SpanTrace]³, custom types¹, source error¹ |
116 | | [thiserror] | New Type | no | context | Backtrace²⁺³, custom types, source error |
117 | | [tracing_error] | Hybrid | yes | [SpanTrace] | only [SpanTrace] |
118 | | [culprit] | Hybrid | no | context, enriched | strings, custom types, source error |
119 |
120 | ¹ Runtime retrieval requires `TypeId` lookup
121 | ² Requires Rust nightly
122 | ³ Optional feature
123 |
124 | The first thing you may notice is that most of the error handling crates use unsafe. They do this for varying reasons, but the most common use case I found is to support dynamic extraction of nested types at runtime. Examples: [anyhow:downcast_ref] and [error-stack:downcast_ref]. This is a perfectly fine decision, however I believe it comes with some important tradeoffs. The first is crate complexity. The machinery required to store and retrieve values by type involves a lot of very tricky unsafe usage and some clever typesystem shenanigans to keep the Rust compiler happy. The second tradeoff is that it obfuscates the set of possible erroneous states by hiding that information from the typesystem.
125 |
126 | > [!NOTE]
127 | > When [error_generic_member_access] finally stabilizes, these crates may choose to eliminate some or all of their unsafe usage by switching to `Error::provide`. However it's not clear if or when this feature will land as the error working group seems to be somewhat abandoned as of January 2025.
128 |
129 | Returning to the [table], the next interesting feature is how the crate captures the error's [logical-trace]. I've summarized this with three labels: **context**, **enriched**, and **[SpanTrace]**.
130 |
131 | * **context**: The logical-trace is captured as additional context is accumulated by the error type.
132 | * **enriched**: The logical-trace is automatically enriched with file names and line numbers as context is accumulated.
133 | * **[SpanTrace]**: The current [tracing]::Span is captured and can be used later to query or print out the tree of Spans that led to the instantiation of an error. See [tracing_error] for more details.
134 |
135 | Finally, the [table] outlines the various ways context can be captured:
136 |
137 | * **strings**: Strings may be attached as context as the error propagates.
138 | * **Backtrace**: A [Backtrace] is generated when the error is captured.
139 | * **custom types**: A user defined type is attached as context. In Accumulator style crates the type is erased and may only be retrieved through runtime reflection.
140 | * **source error**: An unenriched error is captured as the "source". For example an underlying `io::Error` is stored as context as the root cause.
141 | * **[SpanTrace]**: The current [tracing]::Span is stored as context when the error is captured.
142 |
143 | With these details in mind, we can finally discuss what makes Culprit unique. Per the table, Culprit is a Hybrid between the New Type and Accumulator model. It's generic over a `Context` type which is provided by the developer. Internally, Culprit builds a [logical-trace] of physical source code locations, context changes, and notes. The combination of a dynamic [logical-trace] with a custom `Context` type provides a best-of-both-worlds experience.
144 |
145 | When using Culprit, the highest level `Context` types should represent all the erroneous states a program can be in. These higher level types will wrap lower level `Context` types all the way down to the root cause of each error state. Because Culprit automatically captures human-readable details in the [logical-trace], the `Context` types are free to only capture what the program needs to handle error states. This allows `Context` types to be closer to a pure representation of the various error states a program can be in.
146 |
147 | One of Culprit's goals is to make it easier for the developer to map erroneous states to error codes. This is useful when writing developer facing binaries or APIs. Culprit suggests that by keeping the `Context` as simple as possible, error codes can be defined as a mapping between paths through the `Context` type and a set of error codes. I accept that you can also achieve this statically with [thiserror] or dynamically via reflection in the other error libraries. However, I believe Culprit is the first crate to make this an explicit design goal and I hope to develop methods to make managing this error code mapping easier.
148 |
149 | # Outstanding Work
150 |
151 | - [x] prefix result extension fns with `or_` to be more idiomatic
152 | - [x] context fns should return `Into`
153 | - [ ] implement `#[derive(CulpritContext)]`
154 | - [ ] provides `Display` attr and impl
155 | - [ ] provides `From` impls for deriving Contexts from Errors or other Contexts. Would be nice to support mapping/extraction.
156 | - [ ] provides `Into>` impl for raising new errors
157 | - [x] rename `Fingerprint` to `Context`
158 | - [ ] add [SpanTrace] support behind a featureflag
159 | - [x] add `type Result = Result>`
160 | - [ ] `bail!` or similar macro for easy error generation
161 | - [ ] document all methods and modules
162 |
163 | [table]: #comparison-table
164 | [logical-trace]: #logical-trace
165 |
166 | [anyhow]:https://docs.rs/anyhow/latest/anyhow/
167 | [error-stack]: https://docs.rs/error-stack/0.5.0/error_stack/
168 | [eyre]: https://docs.rs/eyre/latest/eyre/
169 | [thiserror]:https://docs.rs/thiserror/latest/thiserror/
170 | [tracing_error]: https://docs.rs/tracing-error/latest/tracing_error/
171 | [culprit]: https://docs.rs/culprit/latest/culprit/
172 | [SpanTrace]: https://docs.rs/tracing-error/latest/tracing_error/struct.SpanTrace.html
173 | [anyhow:downcast_ref]: https://docs.rs/anyhow/1.0.95/anyhow/struct.Error.html#method.downcast_ref
174 | [error-stack:downcast_ref]: https://docs.rs/error-stack/0.5.0/error_stack/struct.Report.html
175 | [error_generic_member_access]: https://github.com/rust-lang/rust/issues/99301
176 | [tracing]: https://docs.rs/tracing/latest/tracing/index.html
177 | [Backtrace]: https://doc.rust-lang.org/std/backtrace/index.html
--------------------------------------------------------------------------------
/examples/basic.rs:
--------------------------------------------------------------------------------
1 | use std::{error::Error, fmt::Display};
2 |
3 | use culprit::{Culprit, ResultExt};
4 |
5 | #[derive(Debug)]
6 | struct SimpleError;
7 | impl Error for SimpleError {}
8 | impl Display for SimpleError {
9 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10 | write!(f, "SimpleError")
11 | }
12 | }
13 |
14 | #[derive(Debug)]
15 | enum Context {
16 | A,
17 | }
18 |
19 | impl Display for Context {
20 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 | write!(f, "Context::A")
22 | }
23 | }
24 |
25 | impl From for Context {
26 | fn from(_: SimpleError) -> Self {
27 | Context::A
28 | }
29 | }
30 |
31 | #[derive(Debug)]
32 | enum Context2 {
33 | Wrapped(Context),
34 | }
35 |
36 | impl Display for Context2 {
37 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 | match self {
39 | Context2::Wrapped(x) => write!(f, "Context2::Wrapped({x})"),
40 | }
41 | }
42 | }
43 |
44 | impl From for Context2 {
45 | fn from(_: Context) -> Self {
46 | Context2::Wrapped(Context::A)
47 | }
48 | }
49 |
50 | fn raise_simple_error() -> Result<(), SimpleError> {
51 | Err(SimpleError)
52 | }
53 |
54 | fn wrap_in_culprit() -> Result<(), Culprit> {
55 | raise_simple_error()?;
56 | Ok(())
57 | }
58 |
59 | fn map_context() -> Result<(), Culprit> {
60 | wrap_in_culprit().or_into_ctx()?;
61 | Ok(())
62 | }
63 |
64 | fn add_note() -> Result<(), Culprit> {
65 | map_context().or_into_culprit("This is a note")?;
66 | Ok(())
67 | }
68 |
69 | fn map_context_without_changing() -> Result<(), Culprit> {
70 | add_note().or_into_ctx()?;
71 | Ok(())
72 | }
73 |
74 | pub fn main() {
75 | let culprit = map_context_without_changing().unwrap_err();
76 | println!("{:?}", culprit);
77 |
78 | assert!(matches!(culprit.ctx(), &Context2::Wrapped(Context::A)));
79 | let context = culprit.trace();
80 | assert_eq!(context.len(), 4);
81 | }
82 |
--------------------------------------------------------------------------------
/examples/file.rs:
--------------------------------------------------------------------------------
1 | //! A simple example program which parses a file as a JSON array and then sums
2 | //! the values. All errors are handled by Culprit.
3 | //!
4 | //! This program is overengineered on purpose to demonstrate multiple
5 | //! abstraction layers and showcase more of Culprit's functionality.
6 | //!
7 | //! Here are some example invocations:
8 | //!
9 | //! ```sh
10 | //! # missing an argument
11 | //! cargo run --example file
12 | //!
13 | //! # missing file
14 | //! cargo run --example file missing.json
15 | //!
16 | //! # bad JSON array contents
17 | //! cargo run --example file examples/json/bad.json
18 | //!
19 | //! # good JSON array contents
20 | //! cargo run --example file examples/json/good.json
21 | //! ```
22 |
23 | use culprit::{Culprit, ResultExt};
24 |
25 | mod file {
26 | use culprit::{Culprit, ResultExt};
27 | use std::{
28 | fmt::{Display, Formatter},
29 | path::Path,
30 | };
31 |
32 | #[derive(Debug)]
33 | pub enum FileCtx {
34 | Io(std::io::ErrorKind),
35 | Corrupt,
36 | }
37 |
38 | impl Display for FileCtx {
39 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40 | match self {
41 | FileCtx::Io(kind) => write!(f, "I/O error: {}", kind),
42 | FileCtx::Corrupt => write!(f, "corrupt data"),
43 | }
44 | }
45 | }
46 |
47 | impl From for FileCtx {
48 | fn from(err: std::io::Error) -> Self {
49 | FileCtx::Io(err.kind())
50 | }
51 | }
52 |
53 | pub fn read_file>(path: P) -> Result, Culprit> {
54 | let file = std::fs::File::open(&path)?;
55 | let reader = std::io::BufReader::new(file);
56 | let data = serde_json::from_reader(reader).or_ctx(|_| FileCtx::Corrupt)?;
57 | Ok(data)
58 | }
59 | }
60 |
61 | mod calc {
62 | use crate::file;
63 | use culprit::{Culprit, ResultExt};
64 | use std::path::Path;
65 |
66 | #[derive(Debug)]
67 | pub enum CalcCtx {
68 | NotANumber,
69 | File(file::FileCtx),
70 | }
71 |
72 | impl std::fmt::Display for CalcCtx {
73 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 | match self {
75 | CalcCtx::NotANumber => write!(f, "not a number"),
76 | CalcCtx::File(fp) => write!(f, "{}", fp),
77 | }
78 | }
79 | }
80 |
81 | impl From for CalcCtx {
82 | fn from(fp: file::FileCtx) -> Self {
83 | CalcCtx::File(fp)
84 | }
85 | }
86 |
87 | pub fn sum_file>(path: P) -> Result> {
88 | let data = file::read_file(&path).or_into_ctx()?;
89 | let mut sum = 0f64;
90 | for value in data {
91 | match value {
92 | serde_json::Value::Number(n) => {
93 | sum += n
94 | .as_f64()
95 | .ok_or_else(|| Culprit::new(CalcCtx::NotANumber))?
96 | }
97 | other => {
98 | return Err(Culprit::new_with_note(
99 | CalcCtx::NotANumber,
100 | format!("expected number; got {:?}", other),
101 | ))
102 | }
103 | }
104 | }
105 | Ok(sum)
106 | }
107 | }
108 |
109 | #[derive(Debug)]
110 | pub enum Ctx {
111 | Calc(calc::CalcCtx),
112 | Usage,
113 | }
114 |
115 | impl std::fmt::Display for Ctx {
116 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 | match self {
118 | Ctx::Calc(fp) => write!(f, "{}", fp),
119 | Ctx::Usage => write!(f, "usage error; expected one argument"),
120 | }
121 | }
122 | }
123 |
124 | impl From for Ctx {
125 | fn from(fp: calc::CalcCtx) -> Self {
126 | Ctx::Calc(fp)
127 | }
128 | }
129 |
130 | pub fn main() -> Result<(), Culprit> {
131 | let path = std::env::args()
132 | .nth(1)
133 | .ok_or_else(|| Culprit::new(Ctx::Usage))?;
134 | let sum = calc::sum_file(&path).or_into_ctx()?;
135 | println!("Sum: {}", sum);
136 | Ok(())
137 | }
138 |
--------------------------------------------------------------------------------
/examples/json/bad.json:
--------------------------------------------------------------------------------
1 | [
2 | 1,
3 | "hello",
4 | 3.5
5 | ]
--------------------------------------------------------------------------------
/examples/json/good.json:
--------------------------------------------------------------------------------
1 | [
2 | 1,
3 | 2,
4 | 3.5
5 | ]
--------------------------------------------------------------------------------
/src/context.rs:
--------------------------------------------------------------------------------
1 | use core::fmt::Debug;
2 | use core::fmt::Display;
3 |
4 | pub trait Context: Display + Debug + Send + Sync + 'static {}
5 |
6 | impl Context for T {}
7 |
--------------------------------------------------------------------------------
/src/culprit.rs:
--------------------------------------------------------------------------------
1 | use alloc::borrow::Cow;
2 | use alloc::string::ToString;
3 | use core::{
4 | error::Error,
5 | fmt::{Debug, Display, Formatter},
6 | };
7 |
8 | use crate::{
9 | context::Context,
10 | trace::{Trace, TracePoint},
11 | };
12 |
13 | #[derive(Clone)]
14 | pub struct Culprit {
15 | ctx: C,
16 | stack: Trace,
17 | }
18 |
19 | impl Culprit {
20 | #[inline]
21 | #[track_caller]
22 | pub fn new(ctx: C) -> Self {
23 | let stack = Trace::from_ctx(TracePoint::new(ctx.to_string()));
24 | Self { ctx, stack }
25 | }
26 |
27 | #[inline]
28 | #[track_caller]
29 | pub fn new_with_note>>(ctx: C, note: N) -> Self {
30 | let stack = Trace::from_ctx(TracePoint::new(note));
31 | Self { ctx, stack }
32 | }
33 |
34 | #[inline]
35 | pub fn new_with_stack(ctx: impl Into, stack: Trace) -> Self {
36 | Self {
37 | ctx: ctx.into(),
38 | stack,
39 | }
40 | }
41 |
42 | #[inline]
43 | #[track_caller]
44 | pub fn from_err>(err: E) -> Self {
45 | let stack = Trace::from_err(&err);
46 | let ctx = err.into();
47 | Self { ctx, stack }
48 | }
49 |
50 | #[inline]
51 | #[track_caller]
52 | pub fn with_note>>(mut self, note: I) -> Self {
53 | self.stack.push(TracePoint::new(note));
54 | self
55 | }
56 |
57 | #[inline]
58 | #[track_caller]
59 | pub fn map_ctx(self, map: F) -> Culprit
60 | where
61 | C2: Context + From,
62 | F: FnOnce(C) -> I,
63 | {
64 | Culprit {
65 | ctx: map(self.ctx).into(),
66 | stack: self.stack,
67 | }
68 | }
69 |
70 | #[inline]
71 | pub fn ctx(&self) -> &C {
72 | &self.ctx
73 | }
74 |
75 | #[inline]
76 | pub fn trace(&self) -> &Trace {
77 | &self.stack
78 | }
79 |
80 | #[inline]
81 | pub fn into_err(self) -> CulpritErr {
82 | CulpritErr(self)
83 | }
84 | }
85 |
86 | impl> From for Culprit {
87 | #[inline]
88 | #[track_caller]
89 | fn from(source: E) -> Self {
90 | Self::from_err(source)
91 | }
92 | }
93 |
94 | impl From> for (C, Trace) {
95 | #[inline]
96 | fn from(culprit: Culprit) -> Self {
97 | (culprit.ctx, culprit.stack)
98 | }
99 | }
100 |
101 | impl Debug for Culprit {
102 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
103 | write!(f, "{:?}\n{}", self.ctx, self.stack)?;
104 | Ok(())
105 | }
106 | }
107 |
108 | impl Display for Culprit {
109 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
110 | write!(f, "{}\n{}", self.ctx, self.stack)?;
111 | Ok(())
112 | }
113 | }
114 |
115 | pub struct CulpritErr(Culprit);
116 |
117 | impl CulpritErr {
118 | #[inline]
119 | pub fn into_culprit(self) -> Culprit {
120 | self.0
121 | }
122 | }
123 |
124 | impl Display for CulpritErr {
125 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
126 | Display::fmt(&self.0, f)
127 | }
128 | }
129 |
130 | impl Debug for CulpritErr {
131 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
132 | Debug::fmt(&self.0, f)
133 | }
134 | }
135 |
136 | impl Error for CulpritErr {}
137 |
138 | #[cfg(test)]
139 | mod tests {
140 | use core::error::Error;
141 | use core::fmt::Display;
142 |
143 | use super::Culprit;
144 |
145 | #[derive(Debug, Clone)]
146 | struct Ctx;
147 |
148 | impl Display for Ctx {
149 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 | write!(f, "Ctx")
151 | }
152 | }
153 |
154 | impl Error for Ctx {}
155 |
156 | #[test]
157 | fn test_clone() {
158 | let culprit = Culprit::new(Ctx);
159 | let _ = culprit.clone();
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | #![cfg_attr(not(test), no_std)]
2 | #![forbid(unsafe_code)]
3 |
4 | extern crate alloc;
5 |
6 | mod context;
7 | mod culprit;
8 | mod result;
9 | mod src_location;
10 | mod trace;
11 |
12 | pub use context::Context;
13 | pub use culprit::{Culprit, CulpritErr};
14 | pub use result::ResultExt;
15 | pub use trace::TracePoint;
16 |
17 | pub type Result = core::result::Result>;
18 |
--------------------------------------------------------------------------------
/src/result.rs:
--------------------------------------------------------------------------------
1 | use alloc::borrow::Cow;
2 | use alloc::string::ToString;
3 | use core::error::Error;
4 |
5 | use crate::{context::Context, culprit::Culprit, trace::Trace};
6 |
7 | pub trait ResultExt {
8 | type Ok;
9 | type Residual;
10 |
11 | #[track_caller]
12 | fn or_ctx(self, op: F) -> Result>
13 | where
14 | F: FnOnce(Self::Residual) -> I,
15 | C: Context + From;
16 |
17 | #[inline]
18 | #[track_caller]
19 | fn or_into_ctx(self) -> Result>
20 | where
21 | Self: Sized,
22 | C: Context + From,
23 | {
24 | self.or_ctx(C::from)
25 | }
26 |
27 | #[inline]
28 | #[track_caller]
29 | fn or_culprit(self, note: N, op: F) -> Result>
30 | where
31 | N: Into>,
32 | F: FnOnce(Self::Residual) -> I,
33 | C: Context + From,
34 | Self: Sized,
35 | {
36 | self.or_ctx(op).map_err(|culprit| culprit.with_note(note))
37 | }
38 |
39 | #[inline]
40 | #[track_caller]
41 | fn or_into_culprit(self, note: N) -> Result>
42 | where
43 | Self: Sized,
44 | C: Context + From,
45 | N: Into>,
46 | {
47 | self.or_culprit(note, C::from)
48 | }
49 | }
50 |
51 | impl ResultExt for core::result::Result {
52 | type Ok = Ok;
53 | type Residual = Err;
54 |
55 | #[track_caller]
56 | fn or_ctx(self, op: F) -> Result>
57 | where
58 | F: FnOnce(Err) -> I,
59 | C: Context + From,
60 | {
61 | match self {
62 | Ok(t) => Ok(t),
63 | Err(e) => {
64 | let stack = Trace::from_err(&e);
65 | Err(Culprit::new_with_stack(op(e), stack))
66 | }
67 | }
68 | }
69 | }
70 |
71 | impl ResultExt for core::result::Result> {
72 | type Ok = Ok;
73 | type Residual = C1;
74 |
75 | #[track_caller]
76 | fn or_ctx(self, op: F) -> Result>
77 | where
78 | F: FnOnce(C1) -> I,
79 | C2: Context + From,
80 | {
81 | match self {
82 | Ok(t) => Ok(t),
83 | Err(culprit) => {
84 | let note = culprit.ctx().to_string();
85 | Err(culprit.map_ctx(op).with_note(note))
86 | }
87 | }
88 | }
89 |
90 | fn or_culprit(self, note: N, op: F) -> Result>
91 | where
92 | N: Into>,
93 | F: FnOnce(C1) -> I,
94 | Self: Sized,
95 | C2: Context + From,
96 | {
97 | match self {
98 | Ok(t) => Ok(t),
99 | Err(culprit) => Err(culprit.map_ctx(op).with_note(note)),
100 | }
101 | }
102 |
103 | fn or_into_culprit(self, note: N) -> Result>
104 | where
105 | Self: Sized,
106 | C2: Context + From,
107 | N: Into>,
108 | {
109 | match self {
110 | Ok(t) => Ok(t),
111 | Err(culprit) => Err(culprit.map_ctx(C2::from).with_note(note)),
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/src_location.rs:
--------------------------------------------------------------------------------
1 | use core::{
2 | fmt::{Debug, Display, Formatter, Result},
3 | panic::Location,
4 | };
5 |
6 | #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
7 | pub struct SrcLocation(&'static Location<'static>);
8 |
9 | impl SrcLocation {
10 | #[inline]
11 | #[track_caller]
12 | pub fn new() -> Self {
13 | Self(Location::caller())
14 | }
15 |
16 | #[inline]
17 | pub fn file(&self) -> &'static str {
18 | self.0.file()
19 | }
20 |
21 | #[inline]
22 | pub fn line(&self) -> u32 {
23 | self.0.line()
24 | }
25 |
26 | #[inline]
27 | pub fn column(&self) -> u32 {
28 | self.0.column()
29 | }
30 | }
31 |
32 | impl From for &'static Location<'static> {
33 | #[inline]
34 | fn from(val: SrcLocation) -> Self {
35 | val.0
36 | }
37 | }
38 |
39 | impl Default for SrcLocation {
40 | #[inline]
41 | #[track_caller]
42 | fn default() -> Self {
43 | Self::new()
44 | }
45 | }
46 |
47 | impl Debug for SrcLocation {
48 | #[inline]
49 | fn fmt(&self, f: &mut Formatter<'_>) -> Result {
50 | f.debug_struct("StaticLocation")
51 | .field("file", &self.0.file())
52 | .field("line", &self.0.line())
53 | .field("column", &self.0.column())
54 | .finish()
55 | }
56 | }
57 |
58 | impl Display for SrcLocation {
59 | #[inline]
60 | fn fmt(&self, f: &mut Formatter<'_>) -> Result {
61 | Display::fmt(&self.0, f)
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/trace.rs:
--------------------------------------------------------------------------------
1 | use alloc::borrow::Cow;
2 | use alloc::string::ToString;
3 | use alloc::vec::Vec;
4 | use core::error::Error;
5 | use core::fmt::{Display, Formatter};
6 | use smallvec::SmallVec;
7 |
8 | use crate::src_location::SrcLocation;
9 |
10 | #[derive(Clone)]
11 | pub struct TracePoint {
12 | location: Option,
13 | note: Cow<'static, str>,
14 | }
15 |
16 | impl TracePoint {
17 | #[track_caller]
18 | pub fn new>>(note: N) -> Self {
19 | Self {
20 | location: Some(SrcLocation::new()),
21 | note: note.into(),
22 | }
23 | }
24 |
25 | pub(crate) fn from_err_source(e: E) -> Self {
26 | Self {
27 | location: None,
28 | note: e.to_string().into(),
29 | }
30 | }
31 | }
32 |
33 | impl Display for TracePoint {
34 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
35 | let note = &self.note;
36 | match &self.location {
37 | None => write!(f, "{note}")?,
38 | Some(loc) => write!(f, "{note}, at {loc}")?,
39 | }
40 | Ok(())
41 | }
42 | }
43 |
44 | #[derive(Default, Clone)]
45 | pub struct Trace(SmallVec<[TracePoint; 1]>);
46 |
47 | impl Trace {
48 | pub fn from_ctx(ctx: TracePoint) -> Self {
49 | Self(SmallVec::from_buf([ctx]))
50 | }
51 |
52 | #[track_caller]
53 | pub fn from_err(err: &E) -> Self {
54 | let ctx = TracePoint::new(err.to_string());
55 | if err.source().is_none() {
56 | // fast path if there is no source
57 | return Self(SmallVec::from_buf([ctx]));
58 | }
59 |
60 | let mut stack = Vec::new();
61 | stack.push(ctx);
62 |
63 | // add all error sources to the trace
64 | let mut source = err.source();
65 | while let Some(err) = source {
66 | stack.push(TracePoint::from_err_source(err));
67 | source = err.source();
68 | }
69 |
70 | // reverse the stack so the the error is at the top
71 | stack.reverse();
72 |
73 | Self(SmallVec::from_vec(stack))
74 | }
75 |
76 | #[inline]
77 | pub fn push(&mut self, ctx: TracePoint) {
78 | self.0.push(ctx);
79 | }
80 |
81 | /// iterate over the trace from the top of the stack to the bottom
82 | #[inline]
83 | pub fn iter(&self) -> impl DoubleEndedIterator- {
84 | self.0.iter().rev()
85 | }
86 |
87 | #[inline]
88 | pub fn len(&self) -> usize {
89 | self.0.len()
90 | }
91 |
92 | #[inline]
93 | pub fn is_empty(&self) -> bool {
94 | self.0.is_empty()
95 | }
96 | }
97 |
98 | impl Display for Trace {
99 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
100 | for (i, ctx) in self.iter().enumerate() {
101 | if i > 0 {
102 | writeln!(f)?;
103 | }
104 | write!(f, "{i}: {ctx}")?;
105 | }
106 | Ok(())
107 | }
108 | }
109 |
--------------------------------------------------------------------------------