├── .gitignore ├── .travis.yml ├── LICENSE ├── Palantir_Corporate_Contributor_License_Agreement.pdf ├── Palantir_Individual_Contributor_License_Agreement.pdf ├── README.md ├── cause.go ├── cause_test.go ├── cleanpath ├── gopath.go └── gopath_test.go ├── codes_for_test.go ├── doc.go ├── format.go ├── format_test.go ├── functions_for_test.go ├── stacktrace.go └── stacktrace_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | stacktrace.iml 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: go 4 | 5 | go: 1.6 6 | 7 | before_install: 8 | - go get github.com/golang/lint/golint 9 | 10 | script: 11 | - go vet ./... 12 | - $HOME/gopath/bin/golint ./... 13 | - go test -v ./... 14 | 15 | notifications: 16 | email: false 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 {yyyy} {name of copyright owner} 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. 202 | -------------------------------------------------------------------------------- /Palantir_Corporate_Contributor_License_Agreement.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/palantir/stacktrace/78658fd2d1772b755720ed8c44367d11ee5380d6/Palantir_Corporate_Contributor_License_Agreement.pdf -------------------------------------------------------------------------------- /Palantir_Individual_Contributor_License_Agreement.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/palantir/stacktrace/78658fd2d1772b755720ed8c44367d11ee5380d6/Palantir_Individual_Contributor_License_Agreement.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stacktrace [![Circle CI](https://img.shields.io/circleci/project/palantir/stacktrace/master.svg?label=circleci)](https://circleci.com/gh/palantir/stacktrace) [![Travis CI](https://img.shields.io/travis/palantir/stacktrace/master.svg?label=travis)](https://travis-ci.org/palantir/stacktrace) 2 | 3 | Look at Palantir, such a Java shop. I can't believe they want stack traces in 4 | their Go code. 5 | 6 | ### Why would anyone want stack traces in Go code? 7 | 8 | This is difficult to debug: 9 | 10 | ``` 11 | Inverse tachyon pulse failed 12 | ``` 13 | 14 | This gives the full story and is easier to debug: 15 | 16 | ``` 17 | Failed to register for villain discovery 18 | --- at github.com/palantir/shield/agent/discovery.go:265 (ShieldAgent.reallyRegister) --- 19 | --- at github.com/palantir/shield/connector/impl.go:89 (Connector.Register) --- 20 | Caused by: Failed to load S.H.I.E.L.D. config from /opt/shield/conf/shield.yaml 21 | --- at github.com/palantir/shield/connector/config.go:44 (withShieldConfig) --- 22 | Caused by: There isn't enough time (4 picoseconds required) 23 | --- at github.com/palantir/shield/axiom/pseudo/resource.go:46 (PseudoResource.Adjust) --- 24 | --- at github.com/palantir/shield/axiom/pseudo/growth.go:110 (reciprocatingPseudo.growDown) --- 25 | --- at github.com/palantir/shield/axiom/pseudo/growth.go:121 (reciprocatingPseudo.verify) --- 26 | Caused by: Inverse tachyon pulse failed 27 | --- at github.com/palantir/shield/metaphysic/tachyon.go:72 (TryPulse) --- 28 | ``` 29 | 30 | Note that stack traces are *not designed to be user-visible*. We have found them 31 | to be valuable in log files of server applications. Nobody wants to see these in 32 | CLI output or a web interface or a return value from library code. 33 | 34 | ## Intent 35 | 36 | The intent is *not* that we capture the exact state of the stack when an error 37 | happens, including every function call. For a library that does that, see 38 | [github.com/go-errors/errors](https://github.com/go-errors/errors). The intent 39 | here is to attach relevant contextual information (messages, variables) at 40 | strategic places along the call stack, keeping stack traces compact and 41 | maximally useful. 42 | 43 | ## Example Usage 44 | 45 | 46 |
 47 | func WriteAll(baseDir string, entities []Entity) error {
 48 |     err := os.MkdirAll(baseDir, 0755)
 49 |     if err != nil {
 50 |         return stacktrace.Propagate(err, "Failed to create base directory")
 51 |     }
 52 |     for _, ent := range entities {
 53 |         path := filepath.Join(baseDir, fileNameForEntity(ent))
 54 |         err = Write(path, ent)
 55 |         if err != nil {
 56 |             return stacktrace.Propagate(err, "Failed to write %v to %s", ent, path)
 57 |         }
 58 |     }
 59 |     return nil
 60 | }
 61 | 
62 | 63 | ## Functions 64 | 65 | #### stacktrace.Propagate(cause error, msg string, vals ...interface{}) error 66 | 67 | Propagate wraps an error to include line number information. This is going to be 68 | your most common stacktrace call. 69 | 70 | As in all of these functions, the `msg` and `vals` work like `fmt.Errorf`. 71 | 72 | The message passed to Propagate should describe the action that failed, 73 | resulting in `cause`. The canonical call looks like this: 74 | 75 |
 76 | result, err := process(arg)
 77 | if err != nil {
 78 |     return nil, stacktrace.Propagate(err, "Failed to process %v", arg)
 79 | }
 80 | 
81 | 82 | To write the message, ask yourself "what does this call do?" What does 83 | `process(arg)` do? It processes ${arg}, so the message is that we failed to 84 | process ${arg}. 85 | 86 | Pay attention that the message is not redundant with the one in `err`. In the 87 | `WriteAll` example above, any error from `os.MkdirAll` will already contain the 88 | path it failed to create, so it would be redundant to include it again in our 89 | message. However, the error from `os.MkdirAll` will not identify that path as 90 | corresponding to the "base directory" so we propagate with that information. 91 | 92 | If it is not possible to add any useful contextual information beyond what is 93 | already included in an error, `msg` can be an empty string: 94 | 95 |
 96 | func Something() error {
 97 |     mutex.Lock()
 98 |     defer mutex.Unlock()
 99 | 
100 |     err := reallySomething()
101 |     return stacktrace.Propagate(err, "")
102 | }
103 | 
104 | 105 | The purpose of `""` as opposed to a separate function is to make you feel a 106 | little guilty every time you do this. 107 | 108 | This example also illustrates the behavior of Propagate when `cause` is nil 109 | – it returns nil as well. There is no need to check `if err != nil`. 110 | 111 | #### stacktrace.NewError(msg string, vals ...interface{}) error 112 | 113 | NewError is a drop-in replacement for `fmt.Errorf` that includes line number 114 | information. The canonical call looks like this: 115 | 116 |
117 | if !IsOkay(arg) {
118 |     return stacktrace.NewError("Expected %v to be okay", arg)
119 | }
120 | 
121 | 122 | ### Error Codes 123 | 124 | Occasionally it can be useful to propagate an error code while unwinding the 125 | stack. For example, a RESTful API may use the error code to set the HTTP status 126 | code. 127 | 128 | The type `stacktrace.ErrorCode` is a typedef for uint16. You name the set of 129 | error codes relevant to your application. 130 | 131 | ``` 132 | const ( 133 | EcodeManifestNotFound = stacktrace.ErrorCode(iota) 134 | EcodeBadInput 135 | EcodeTimeout 136 | ) 137 | ``` 138 | 139 | The special value `stacktrace.NoCode` is equal to `math.MaxUint16`, so avoid 140 | using that. NoCode is the error code of errors with no code explicitly attached. 141 | 142 | An ordinary `stacktrace.Propagate` preserves the error code of an error. 143 | 144 | #### stacktrace.PropagateWithCode(cause error, code ErrorCode, msg string, vals ...interface{}) error 145 | 146 | #### stacktrace.NewErrorWithCode(code ErrorCode, msg string, vals ...interface{}) error 147 | 148 | PropagateWithCode and NewErrorWithCode are analogous to Propagate and NewError 149 | but also attach an error code. 150 | 151 |
152 | _, err := os.Stat(manifestPath)
153 | if os.IsNotExist(err) {
154 |     return stacktrace.PropagateWithCode(err, EcodeManifestNotFound, "")
155 | }
156 | 
157 | 158 | #### stacktrace.NewMessageWithCode(code ErrorCode, msg string, vals ...interface{}) error 159 | 160 | The error code mechanism can be useful by itself even where stack traces with 161 | line numbers are not required. NewMessageWithCode returns an error that prints 162 | just like `fmt.Errorf` with no line number, but including a code. 163 | 164 |
165 | ttl := req.URL.Query().Get("ttl")
166 | if ttl == "" {
167 |     return 0, stacktrace.NewMessageWithCode(EcodeBadInput, "Missing ttl query parameter")
168 | }
169 | 
170 | 171 | #### stacktrace.GetCode(err error) ErrorCode 172 | 173 | GetCode extracts the error code from an error. 174 | 175 |
176 | for i := 0; i < attempts; i++ {
177 |     err := Do()
178 |     if stacktrace.GetCode(err) != EcodeTimeout {
179 |         return err
180 |     }
181 |     // try a few more times
182 | }
183 | return stacktrace.NewError("timed out after %d attempts", attempts)
184 | 
185 | 186 | GetCode returns the special value `stacktrace.NoCode` if `err` is nil or if 187 | there is no error code attached to `err`. 188 | 189 | ## License 190 | 191 | Stacktrace is released by Palantir Technologies, Inc. under the Apache 2.0 192 | License. See the included [LICENSE](LICENSE) file for details. 193 | 194 | ## Contributing 195 | 196 | We welcome contributions of backward-compatible changes to this library. 197 | 198 | - Write your code 199 | - Add tests for new functionality 200 | - Run `go test` and verify that the tests pass 201 | - Fill out the [Individual](https://github.com/palantir/stacktrace/blob/master/Palantir_Individual_Contributor_License_Agreement.pdf?raw=true) or [Corporate](https://github.com/palantir/stacktrace/blob/master/Palantir_Corporate_Contributor_License_Agreement.pdf?raw=true) Contributor License Agreement and send it to [opensource@palantir.com](mailto:opensource@palantir.com) 202 | - Submit a pull request 203 | -------------------------------------------------------------------------------- /cause.go: -------------------------------------------------------------------------------- 1 | package stacktrace 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | /* 8 | RootCause unwraps the original error that caused the current one. 9 | 10 | _, err := f() 11 | if perr, ok := stacktrace.RootCause(err).(*ParsingError); ok { 12 | showError(perr.Line, perr.Column, perr.Text) 13 | } 14 | */ 15 | func RootCause(err error) error { 16 | for { 17 | st, ok := err.(*stacktrace) 18 | if !ok { 19 | return err 20 | } 21 | if st.cause == nil { 22 | return errors.New(st.message) 23 | } 24 | err = st.cause 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /cause_test.go: -------------------------------------------------------------------------------- 1 | package stacktrace_test 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | 9 | "github.com/palantir/stacktrace" 10 | ) 11 | 12 | type customError string 13 | 14 | func (e customError) Error() string { return string(e) } 15 | 16 | func TestRootCause(t *testing.T) { 17 | for _, test := range []struct { 18 | err error 19 | rootCause error 20 | }{ 21 | { 22 | err: nil, 23 | rootCause: nil, 24 | }, 25 | { 26 | err: errors.New("msg"), 27 | rootCause: errors.New("msg"), 28 | }, 29 | { 30 | err: stacktrace.NewError("msg"), 31 | rootCause: errors.New("msg"), 32 | }, 33 | { 34 | err: stacktrace.Propagate(stacktrace.NewError("msg1"), "msg2"), 35 | rootCause: errors.New("msg1"), 36 | }, 37 | { 38 | err: customError("msg"), 39 | rootCause: customError("msg"), 40 | }, 41 | { 42 | err: stacktrace.Propagate(customError("msg1"), "msg2"), 43 | rootCause: customError("msg1"), 44 | }, 45 | } { 46 | assert.Equal(t, test.rootCause, stacktrace.RootCause(test.err)) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cleanpath/gopath.go: -------------------------------------------------------------------------------- 1 | package cleanpath 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | "sort" 7 | "strings" 8 | ) 9 | 10 | /* 11 | RemoveGoPath makes a path relative to one of the src directories in the $GOPATH 12 | environment variable. If $GOPATH is empty or the input path is not contained 13 | within any of the src directories in $GOPATH, the original path is returned. If 14 | the input path is contained within multiple of the src directories in $GOPATH, 15 | it is made relative to the longest one of them. 16 | */ 17 | func RemoveGoPath(path string) string { 18 | dirs := filepath.SplitList(os.Getenv("GOPATH")) 19 | // Sort in decreasing order by length so the longest matching prefix is removed 20 | sort.Stable(longestFirst(dirs)) 21 | for _, dir := range dirs { 22 | srcdir := filepath.Join(dir, "src") 23 | rel, err := filepath.Rel(srcdir, path) 24 | // filepath.Rel can traverse parent directories, don't want those 25 | if err == nil && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { 26 | return rel 27 | } 28 | } 29 | return path 30 | } 31 | 32 | type longestFirst []string 33 | 34 | func (strs longestFirst) Len() int { return len(strs) } 35 | func (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) } 36 | func (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] } 37 | -------------------------------------------------------------------------------- /cleanpath/gopath_test.go: -------------------------------------------------------------------------------- 1 | package cleanpath_test 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | 11 | "github.com/palantir/stacktrace/cleanpath" 12 | ) 13 | 14 | func TestRemoveGoPath(t *testing.T) { 15 | for _, testcase := range []struct { 16 | gopath []string 17 | path string 18 | expected string 19 | }{ 20 | { 21 | // empty gopath 22 | gopath: []string{}, 23 | path: "/some/dir/src/pkg/prog.go", 24 | expected: "/some/dir/src/pkg/prog.go", 25 | }, 26 | { 27 | // single matching dir in gopath 28 | gopath: []string{"/some/dir"}, 29 | path: "/some/dir/src/pkg/prog.go", 30 | expected: "pkg/prog.go", 31 | }, 32 | { 33 | // nonmatching dir in gopath 34 | gopath: []string{"/other/dir"}, 35 | path: "/some/dir/src/pkg/prog.go", 36 | expected: "/some/dir/src/pkg/prog.go", 37 | }, 38 | { 39 | // multiple matching dirs in gopath, shorter first 40 | gopath: []string{"/some", "/some/src/dir"}, 41 | path: "/some/src/dir/src/pkg/prog.go", 42 | expected: "pkg/prog.go", 43 | }, 44 | { 45 | // multiple matching dirs in gopath, longer first 46 | gopath: []string{"/some/src/dir", "/some"}, 47 | path: "/some/src/dir/src/pkg/prog.go", 48 | expected: "pkg/prog.go", 49 | }, 50 | } { 51 | gopath := strings.Join(testcase.gopath, string(filepath.ListSeparator)) 52 | err := os.Setenv("GOPATH", gopath) 53 | assert.NoError(t, err, "error setting gopath") 54 | 55 | cleaned := cleanpath.RemoveGoPath(testcase.path) 56 | assert.Equal(t, testcase.expected, cleaned, "testcase: %+v", testcase) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /codes_for_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package stacktrace_test 16 | 17 | import ( 18 | "github.com/palantir/stacktrace" 19 | ) 20 | 21 | const ( 22 | EcodeInvalidVillain = stacktrace.ErrorCode(iota) 23 | EcodeNoSuchPseudo 24 | EcodeNotFastEnough 25 | EcodeTimeIsIllusion 26 | EcodeNotImplemented 27 | ) 28 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /* 16 | Package stacktrace provides functions for wrapping an error to include line 17 | number and/or error code information. 18 | 19 | A stacktrace produced by this package looks like this: 20 | 21 | Failed to register for villain discovery 22 | --- at github.com/palantir/shield/agent/discovery.go:265 (ShieldAgent.reallyRegister) --- 23 | --- at github.com/palantir/shield/connector/impl.go:89 (Connector.Register) --- 24 | Caused by: Failed to load S.H.I.E.L.D. config from /opt/shield/conf/shield.yaml 25 | --- at github.com/palantir/shield/connector/config.go:44 (withShieldConfig) --- 26 | Caused by: There isn't enough time (4 picoseconds required) 27 | --- at github.com/palantir/shield/axiom/pseudo/resource.go:46 (PseudoResource.Adjust) --- 28 | --- at github.com/palantir/shield/axiom/pseudo/growth.go:110 (reciprocatingPseudo.growDown) --- 29 | --- at github.com/palantir/shield/axiom/pseudo/growth.go:121 (reciprocatingPseudo.verify) --- 30 | Caused by: Inverse tachyon pulse failed 31 | --- at github.com/palantir/shield/metaphysic/tachyon.go:72 (TryPulse) --- 32 | 33 | Note that stack traces are not designed to be user-visible. They can be valuable 34 | in a log file of a server application, but nobody wants to see one of them in 35 | CLI output or a web interface or a return value from library code. 36 | */ 37 | package stacktrace 38 | -------------------------------------------------------------------------------- /format.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package stacktrace 16 | 17 | import ( 18 | "fmt" 19 | "strings" 20 | ) 21 | 22 | /* 23 | DefaultFormat defines the behavior of err.Error() when called on a stacktrace, 24 | as well as the default behavior of the "%v", "%s" and "%q" formatting 25 | specifiers. By default, all of these produce a full stacktrace including line 26 | number information. To have them produce a condensed single-line output, set 27 | this value to stacktrace.FormatBrief. 28 | 29 | The formatting specifier "%+s" can be used to force a full stacktrace regardless 30 | of the value of DefaultFormat. Similarly, the formatting specifier "%#s" can be 31 | used to force a brief output. 32 | */ 33 | var DefaultFormat = FormatFull 34 | 35 | // Format is the type of the two possible values of stacktrace.DefaultFormat. 36 | type Format int 37 | 38 | const ( 39 | // FormatFull means format as a full stacktrace including line number information. 40 | FormatFull Format = iota 41 | // FormatBrief means Format on a single line without line number information. 42 | FormatBrief 43 | ) 44 | 45 | var _ fmt.Formatter = (*stacktrace)(nil) 46 | 47 | func (st *stacktrace) Format(f fmt.State, c rune) { 48 | var text string 49 | if f.Flag('+') && !f.Flag('#') && c == 's' { // "%+s" 50 | text = formatFull(st) 51 | } else if f.Flag('#') && !f.Flag('+') && c == 's' { // "%#s" 52 | text = formatBrief(st) 53 | } else { 54 | text = map[Format]func(*stacktrace) string{ 55 | FormatFull: formatFull, 56 | FormatBrief: formatBrief, 57 | }[DefaultFormat](st) 58 | } 59 | 60 | formatString := "%" 61 | // keep the flags recognized by fmt package 62 | for _, flag := range "-+# 0" { 63 | if f.Flag(int(flag)) { 64 | formatString += string(flag) 65 | } 66 | } 67 | if width, has := f.Width(); has { 68 | formatString += fmt.Sprint(width) 69 | } 70 | if precision, has := f.Precision(); has { 71 | formatString += "." 72 | formatString += fmt.Sprint(precision) 73 | } 74 | formatString += string(c) 75 | fmt.Fprintf(f, formatString, text) 76 | } 77 | 78 | func formatFull(st *stacktrace) string { 79 | var str string 80 | newline := func() { 81 | if str != "" && !strings.HasSuffix(str, "\n") { 82 | str += "\n" 83 | } 84 | } 85 | 86 | for curr, ok := st, true; ok; curr, ok = curr.cause.(*stacktrace) { 87 | str += curr.message 88 | 89 | if curr.file != "" { 90 | newline() 91 | if curr.function == "" { 92 | str += fmt.Sprintf(" --- at %v:%v ---", curr.file, curr.line) 93 | } else { 94 | str += fmt.Sprintf(" --- at %v:%v (%v) ---", curr.file, curr.line, curr.function) 95 | } 96 | } 97 | 98 | if curr.cause != nil { 99 | newline() 100 | if cause, ok := curr.cause.(*stacktrace); !ok { 101 | str += "Caused by: " 102 | str += curr.cause.Error() 103 | } else if cause.message != "" { 104 | str += "Caused by: " 105 | } 106 | } 107 | } 108 | 109 | return str 110 | } 111 | 112 | func formatBrief(st *stacktrace) string { 113 | var str string 114 | concat := func(msg string) { 115 | if str != "" && msg != "" { 116 | str += ": " 117 | } 118 | str += msg 119 | } 120 | 121 | curr := st 122 | for { 123 | concat(curr.message) 124 | if cause, ok := curr.cause.(*stacktrace); ok { 125 | curr = cause 126 | } else { 127 | break 128 | } 129 | } 130 | if curr.cause != nil { 131 | concat(curr.cause.Error()) 132 | } 133 | return str 134 | } 135 | -------------------------------------------------------------------------------- /format_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package stacktrace_test 16 | 17 | import ( 18 | "errors" 19 | "fmt" 20 | "regexp" 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/palantir/stacktrace" 26 | ) 27 | 28 | func TestFormat(t *testing.T) { 29 | plainErr := errors.New("plain") 30 | stacktraceErr := stacktrace.Propagate(plainErr, "decorated") 31 | digits := regexp.MustCompile(`\d`) 32 | 33 | for _, test := range []struct { 34 | format stacktrace.Format 35 | specifier string 36 | expectedPlain string 37 | expectedStacktrace string 38 | }{ 39 | { 40 | format: stacktrace.FormatFull, 41 | specifier: "%v", 42 | expectedPlain: "plain", 43 | expectedStacktrace: "decorated\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\nCaused by: plain", 44 | }, 45 | { 46 | format: stacktrace.FormatFull, 47 | specifier: "%q", 48 | expectedPlain: "\"plain\"", 49 | expectedStacktrace: "\"decorated\\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\\nCaused by: plain\"", 50 | }, 51 | { 52 | format: stacktrace.FormatFull, 53 | specifier: "%105s", 54 | expectedPlain: " plain", 55 | expectedStacktrace: " decorated\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\nCaused by: plain", 56 | }, 57 | { 58 | format: stacktrace.FormatFull, 59 | specifier: "%#s", 60 | expectedPlain: "plain", 61 | expectedStacktrace: "decorated: plain", 62 | }, 63 | { 64 | format: stacktrace.FormatBrief, 65 | specifier: "%v", 66 | expectedPlain: "plain", 67 | expectedStacktrace: "decorated: plain", 68 | }, 69 | { 70 | format: stacktrace.FormatBrief, 71 | specifier: "%q", 72 | expectedPlain: "\"plain\"", 73 | expectedStacktrace: "\"decorated: plain\"", 74 | }, 75 | { 76 | format: stacktrace.FormatBrief, 77 | specifier: "%20s", 78 | expectedPlain: " plain", 79 | expectedStacktrace: " decorated: plain", 80 | }, 81 | { 82 | format: stacktrace.FormatBrief, 83 | specifier: "%+s", 84 | expectedPlain: "plain", 85 | expectedStacktrace: "decorated\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\nCaused by: plain", 86 | }, 87 | } { 88 | stacktrace.DefaultFormat = test.format 89 | 90 | actualPlain := fmt.Sprintf(test.specifier, plainErr) 91 | assert.Equal(t, test.expectedPlain, actualPlain) 92 | 93 | actualStacktrace := fmt.Sprintf(test.specifier, stacktraceErr) 94 | actualStacktrace = digits.ReplaceAllString(actualStacktrace, "#") 95 | assert.Equal(t, test.expectedStacktrace, actualStacktrace) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /functions_for_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package stacktrace_test 16 | 17 | import ( 18 | "github.com/palantir/stacktrace" 19 | ) 20 | 21 | type PublicObj struct{} 22 | type privateObj struct{} 23 | type ptrObj struct{} 24 | 25 | func startDoing() error { 26 | return stacktrace.NewError("%s %s %s %s", "failed", "to", "start", "doing") 27 | } 28 | 29 | func (PublicObj) DoPublic(err error) error { 30 | return stacktrace.Propagate(err, "") 31 | } 32 | 33 | func (PublicObj) doPrivate(err error) error { 34 | return stacktrace.Propagate(err, "") 35 | } 36 | 37 | func (privateObj) DoPublic(err error) error { 38 | return stacktrace.Propagate(err, "") 39 | } 40 | 41 | func (privateObj) doPrivate(err error) error { 42 | return stacktrace.Propagate(err, "") 43 | } 44 | 45 | func (*ptrObj) doPtr(err error) error { 46 | return stacktrace.Propagate(err, "pointedly") 47 | } 48 | 49 | func doClosure(err error) error { 50 | return func() error { 51 | return stacktrace.Propagate(err, "so closed") 52 | }() 53 | } 54 | -------------------------------------------------------------------------------- /stacktrace.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package stacktrace 16 | 17 | import ( 18 | "fmt" 19 | "math" 20 | "runtime" 21 | "strings" 22 | 23 | "github.com/palantir/stacktrace/cleanpath" 24 | ) 25 | 26 | /* 27 | CleanPath function is applied to file paths before adding them to a stacktrace. 28 | By default, it makes the path relative to the $GOPATH environment variable. 29 | 30 | To remove some additional prefix like "github.com" from file paths in 31 | stacktraces, use something like: 32 | 33 | stacktrace.CleanPath = func(path string) string { 34 | path = cleanpath.RemoveGoPath(path) 35 | path = strings.TrimPrefix(path, "github.com/") 36 | return path 37 | } 38 | */ 39 | var CleanPath = cleanpath.RemoveGoPath 40 | 41 | /* 42 | NewError is a drop-in replacement for fmt.Errorf that includes line number 43 | information. The canonical call looks like this: 44 | 45 | if !IsOkay(arg) { 46 | return stacktrace.NewError("Expected %v to be okay", arg) 47 | } 48 | */ 49 | func NewError(msg string, vals ...interface{}) error { 50 | return create(nil, NoCode, msg, vals...) 51 | } 52 | 53 | /* 54 | Propagate wraps an error to include line number information. The msg and vals 55 | arguments work like the ones for fmt.Errorf. 56 | 57 | The message passed to Propagate should describe the action that failed, 58 | resulting in the cause. The canonical call looks like this: 59 | 60 | result, err := process(arg) 61 | if err != nil { 62 | return nil, stacktrace.Propagate(err, "Failed to process %v", arg) 63 | } 64 | 65 | To write the message, ask yourself "what does this call do?" What does 66 | process(arg) do? It processes ${arg}, so the message is that we failed to 67 | process ${arg}. 68 | 69 | Pay attention that the message is not redundant with the one in err. If it is 70 | not possible to add any useful contextual information beyond what is already 71 | included in an error, msg can be an empty string: 72 | 73 | func Something() error { 74 | mutex.Lock() 75 | defer mutex.Unlock() 76 | 77 | err := reallySomething() 78 | return stacktrace.Propagate(err, "") 79 | } 80 | 81 | If cause is nil, Propagate returns nil. This allows elision of some "if err != 82 | nil" checks. 83 | */ 84 | func Propagate(cause error, msg string, vals ...interface{}) error { 85 | if cause == nil { 86 | // Allow calling Propagate without checking whether there is error 87 | return nil 88 | } 89 | return create(cause, NoCode, msg, vals...) 90 | } 91 | 92 | /* 93 | ErrorCode is a code that can be attached to an error as it is passed/propagated 94 | up the stack. 95 | 96 | There is no predefined set of error codes. You define the ones relevant to your 97 | application: 98 | 99 | const ( 100 | EcodeManifestNotFound = stacktrace.ErrorCode(iota) 101 | EcodeBadInput 102 | EcodeTimeout 103 | ) 104 | 105 | The one predefined error code is NoCode, which has a value of math.MaxUint16. 106 | Avoid using that value as an error code. 107 | 108 | An ordinary stacktrace.Propagate call preserves the error code of an error. 109 | */ 110 | type ErrorCode uint16 111 | 112 | /* 113 | NoCode is the error code of errors with no code explicitly attached. 114 | */ 115 | const NoCode ErrorCode = math.MaxUint16 116 | 117 | /* 118 | NewErrorWithCode is similar to NewError but also attaches an error code. 119 | */ 120 | func NewErrorWithCode(code ErrorCode, msg string, vals ...interface{}) error { 121 | return create(nil, code, msg, vals...) 122 | } 123 | 124 | /* 125 | PropagateWithCode is similar to Propagate but also attaches an error code. 126 | 127 | _, err := os.Stat(manifestPath) 128 | if os.IsNotExist(err) { 129 | return stacktrace.PropagateWithCode(err, EcodeManifestNotFound, "") 130 | } 131 | */ 132 | func PropagateWithCode(cause error, code ErrorCode, msg string, vals ...interface{}) error { 133 | if cause == nil { 134 | // Allow calling PropagateWithCode without checking whether there is error 135 | return nil 136 | } 137 | return create(cause, code, msg, vals...) 138 | } 139 | 140 | /* 141 | NewMessageWithCode returns an error that prints just like fmt.Errorf with no 142 | line number, but including a code. The error code mechanism can be useful by 143 | itself even where stack traces with line numbers are not warranted. 144 | 145 | ttl := req.URL.Query().Get("ttl") 146 | if ttl == "" { 147 | return 0, stacktrace.NewMessageWithCode(EcodeBadInput, "Missing ttl query parameter") 148 | } 149 | */ 150 | func NewMessageWithCode(code ErrorCode, msg string, vals ...interface{}) error { 151 | return &stacktrace{ 152 | message: fmt.Sprintf(msg, vals...), 153 | code: code, 154 | } 155 | } 156 | 157 | /* 158 | GetCode extracts the error code from an error. 159 | 160 | for i := 0; i < attempts; i++ { 161 | err := Do() 162 | if stacktrace.GetCode(err) != EcodeTimeout { 163 | return err 164 | } 165 | // try a few more times 166 | } 167 | return stacktrace.NewError("timed out after %d attempts", attempts) 168 | 169 | GetCode returns the special value stacktrace.NoCode if err is nil or if there is 170 | no error code attached to err. 171 | */ 172 | func GetCode(err error) ErrorCode { 173 | if err, ok := err.(*stacktrace); ok { 174 | return err.code 175 | } 176 | return NoCode 177 | } 178 | 179 | type stacktrace struct { 180 | message string 181 | cause error 182 | code ErrorCode 183 | file string 184 | function string 185 | line int 186 | } 187 | 188 | func create(cause error, code ErrorCode, msg string, vals ...interface{}) error { 189 | // If no error code specified, inherit error code from the cause. 190 | if code == NoCode { 191 | code = GetCode(cause) 192 | } 193 | 194 | err := &stacktrace{ 195 | message: fmt.Sprintf(msg, vals...), 196 | cause: cause, 197 | code: code, 198 | } 199 | 200 | // Caller of create is NewError or Propagate, so user's code is 2 up. 201 | pc, file, line, ok := runtime.Caller(2) 202 | if !ok { 203 | return err 204 | } 205 | if CleanPath != nil { 206 | file = CleanPath(file) 207 | } 208 | err.file, err.line = file, line 209 | 210 | f := runtime.FuncForPC(pc) 211 | if f == nil { 212 | return err 213 | } 214 | err.function = shortFuncName(f) 215 | 216 | return err 217 | } 218 | 219 | /* "FuncName" or "Receiver.MethodName" */ 220 | func shortFuncName(f *runtime.Func) string { 221 | // f.Name() is like one of these: 222 | // - "github.com/palantir/shield/package.FuncName" 223 | // - "github.com/palantir/shield/package.Receiver.MethodName" 224 | // - "github.com/palantir/shield/package.(*PtrReceiver).MethodName" 225 | longName := f.Name() 226 | 227 | withoutPath := longName[strings.LastIndex(longName, "/")+1:] 228 | withoutPackage := withoutPath[strings.Index(withoutPath, ".")+1:] 229 | 230 | shortName := withoutPackage 231 | shortName = strings.Replace(shortName, "(", "", 1) 232 | shortName = strings.Replace(shortName, "*", "", 1) 233 | shortName = strings.Replace(shortName, ")", "", 1) 234 | 235 | return shortName 236 | } 237 | 238 | func (st *stacktrace) Error() string { 239 | return fmt.Sprint(st) 240 | } 241 | 242 | // ExitCode returns the exit code associated with the stacktrace error based on its error code. If the error code is 243 | // NoCode, return 1 (default); otherwise, returns the value of the error code. 244 | func (st *stacktrace) ExitCode() int { 245 | if st.code == NoCode { 246 | return 1 247 | } 248 | return int(st.code) 249 | } 250 | -------------------------------------------------------------------------------- /stacktrace_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Palantir Technologies 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package stacktrace_test 16 | 17 | import ( 18 | "errors" 19 | "fmt" 20 | "strings" 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/palantir/stacktrace" 26 | ) 27 | 28 | func TestMessage(t *testing.T) { 29 | err := startDoing() 30 | err = PublicObj{}.DoPublic(err) 31 | err = PublicObj{}.doPrivate(err) 32 | err = privateObj{}.DoPublic(err) 33 | err = privateObj{}.doPrivate(err) 34 | err = (&ptrObj{}).doPtr(err) 35 | err = doClosure(err) 36 | 37 | expected := strings.Join([]string{ 38 | "so closed", 39 | " --- at github.com/palantir/stacktrace/functions_for_test.go:51 (doClosure.func1) ---", 40 | "Caused by: pointedly", 41 | " --- at github.com/palantir/stacktrace/functions_for_test.go:46 (ptrObj.doPtr) ---", 42 | " --- at github.com/palantir/stacktrace/functions_for_test.go:42 (privateObj.doPrivate) ---", 43 | " --- at github.com/palantir/stacktrace/functions_for_test.go:38 (privateObj.DoPublic) ---", 44 | " --- at github.com/palantir/stacktrace/functions_for_test.go:34 (PublicObj.doPrivate) ---", 45 | " --- at github.com/palantir/stacktrace/functions_for_test.go:30 (PublicObj.DoPublic) ---", 46 | "Caused by: failed to start doing", 47 | " --- at github.com/palantir/stacktrace/functions_for_test.go:26 (startDoing) ---", 48 | }, "\n") 49 | stacktrace.DefaultFormat = stacktrace.FormatFull 50 | assert.Equal(t, expected, err.Error()) 51 | assert.Equal(t, expected, fmt.Sprint(err)) 52 | } 53 | 54 | func TestGetCode(t *testing.T) { 55 | for _, test := range []struct { 56 | originalError error 57 | originalCode stacktrace.ErrorCode 58 | }{ 59 | { 60 | originalError: errors.New("err"), 61 | originalCode: stacktrace.NoCode, 62 | }, 63 | { 64 | originalError: stacktrace.NewError("err"), 65 | originalCode: stacktrace.NoCode, 66 | }, 67 | { 68 | originalError: stacktrace.NewErrorWithCode(EcodeInvalidVillain, "err"), 69 | originalCode: EcodeInvalidVillain, 70 | }, 71 | { 72 | originalError: stacktrace.NewMessageWithCode(EcodeNoSuchPseudo, "err"), 73 | originalCode: EcodeNoSuchPseudo, 74 | }, 75 | } { 76 | err := test.originalError 77 | assert.Equal(t, test.originalCode, stacktrace.GetCode(err)) 78 | 79 | err = stacktrace.Propagate(err, "") 80 | assert.Equal(t, test.originalCode, stacktrace.GetCode(err)) 81 | 82 | err = stacktrace.PropagateWithCode(err, EcodeNotFastEnough, "") 83 | assert.Equal(t, EcodeNotFastEnough, stacktrace.GetCode(err)) 84 | 85 | err = stacktrace.PropagateWithCode(err, EcodeTimeIsIllusion, "") 86 | assert.Equal(t, EcodeTimeIsIllusion, stacktrace.GetCode(err)) 87 | } 88 | } 89 | 90 | func TestPropagateNil(t *testing.T) { 91 | var err error 92 | 93 | err = stacktrace.Propagate(err, "") 94 | assert.Nil(t, err) 95 | 96 | err = stacktrace.PropagateWithCode(err, EcodeNotImplemented, "") 97 | assert.Nil(t, err) 98 | 99 | assert.Equal(t, stacktrace.NoCode, stacktrace.GetCode(err)) 100 | } 101 | --------------------------------------------------------------------------------