GeezerVison is showing github.com — Proposal: A built-in Go error check function, "try" · Issue #32437 · golang/go
Proposal: A built-in Go error check function, "try" #32437DescriptionProposal: A built-in Go error check function, try
This proposal has been closed. Thanks, everybody, for your input.
Before commenting, please read the detailed design doc and see the discussion summary as of June 6, the summary as of June 10, and most importantly the advice on staying focussed. Your question or suggestion may have already been answered or made. Thanks.
We propose a new built-in function called try, designed specifically to eliminate the boilerplate if statements typically associated with error handling in Go. No other language changes are suggested. We advocate using the existing defer statement and standard library functions to help with augmenting or wrapping of errors. This minimal approach addresses most common scenarios while adding very little complexity to the language. The try built-in is easy to explain, straightforward to implement, orthogonal to other language constructs, and fully backward-compatible. It also leaves open a path to extending the mechanism, should we wish to do so in the future.
[The text below has been edited to reflect the design doc more accurately.]
The try built-in function takes a single expression as argument. The expression must evaluate to n+1 values (where n may be zero) where the last value must be of type error. It returns the first n values (if any) if the (final) error argument is nil, otherwise it returns from the enclosing function with that error. For instance, code such as
f, err := os.Open(filename)
if err != nil {
return …, err // zero values for other results, if any
}
can be simplified to
f := try(os.Open(filename))
try can only be used in a function which itself returns an error result, and that result must be the last result parameter of the enclosing function.
This proposal reduces the original draft design presented at last year's GopherCon to its essence. If error augmentation or wrapping is desired there are two approaches: Stick with the tried-and-true if statement, or, alternatively, “declare” an error handler with a defer statement:
defer func() {
if err != nil { // no error may have occurred - check for it
err = … // wrap/augment error
}
}()
Here, err is the name of the error result of the enclosing function. In practice, suitable helper functions will reduce the declaration of an error handler to a one-liner. For instance
defer fmt.HandleErrorf(&err, "copy %s %s", src, dst)
(where fmt.HandleErrorf decorates *err) reads well and can be implemented without the need for new language features.
The main drawback of this approach is that the error result parameter needs to be named, possibly leading to less pretty APIs. Ultimately this is a matter of style, and we believe we will adapt to expecting the new style, much as we adapted to not having semicolons.
In summary, try may seem unusual at first, but it is simply syntactic sugar tailor-made for one specific task, error handling with less boilerplate, and to handle that task well enough. As such it fits nicely into the philosophy of Go. try is not designed to address all error handling situations; it is designed to handle the most common case well, to keep the design simple and clear.
Credits
This proposal is strongly influenced by the feedback we have received so far. Specifically, it borrows ideas from:
Detailed design doc
https://github.com/golang/proposal/blob/master/design/32437-try-builtin.md
tryhard tool for exploring impact of try
https://github.com/griesemer/tryhard Reacted by Giovanni Bajo, sometimescool22, Yves Junqueira, Jose Luis Ordiales Coscia, Aleksei Kuznetcov, Sakthivel Balasubramaniam, Taichi Nakashima, Eric Rutherford, Bob Strecansky, jdx and 343 more Reacted by Eric Lagergren, Cholerae Hu, Dainius, Conner Fromknecht, Tom Thorogood, Aleksandr Kuznetsov, Alex Giurgiu, Liam Breck, Cassondra Foesch, JonathanPPH and 813 more Reacted by Paul Bauer, Alexey Polev, Jack Rendor, Johmel Pintor, iruyuejun, Hong Shick Pak, general, ghoslin01, Mislav Jakopović, Aleksey Martynenko and 8 more Reacted by An Long, Russell Hernandez Ruiz, Miguel Molina, Georgi N. Georgiev, Vladimir Zhigulin, Mateusz Czapliński, Filippo Valsorda, Ahmed W., Diogo Pinela, Iwan Aucamp and 17 more Reacted by Carlos (Goodwine), Patrick Stephen, Michael Panzer, Cholerae Hu, Conner Fromknecht, Liam Breck, Lukáš Lukáč, Sergey Yarmonov, Andrew Luzin, Mohammed Al Sahaf and 122 more Reacted by Mateusz Czapliński, Russell Hernandez Ruiz, Ahmed W., alanfo, Sascha Matzke, David Ndungu, Iwan Aucamp, LMMilewski, Wilk, Ilya Kaznacheev and 31 more Reacted by Jianfei Wang, Miguel Molina, Georgi N. Georgiev, Bruno Scheufler, Russell Hernandez Ruiz, Michał Suchwałko, Quentin Mazars-Simon, Ahmed W., radhe, Iwan Aucamp and 9 more Reacted by Dominik Honnef, Craig Jellick, stephen, Shude Li, Eric Lagergren, seph, Dmitry Kologrivov, Carlos Alexandro Becker, Kurisu_Amatist, Milad and 37 more Activityrasky commented on Jun 4, 2019 I agree this is the best way forward: fixing the most common issue with a simple design.
I don't want to bikeshed (feel free to postpone this conversation), but Rust went there and eventually settled with the ? postfix operator rather than a builtin function, for increased readability.
The gophercon proposal cites ? in the considered ideas and gives three reason why it was discarded: the first ("control flow transfers are as a general rule accompanied by keywords") and the third ("handlers are more naturally defined with a keyword, so checks should too") do not apply anymore. The second is stylistic: it says that, even if the postfix operator works better for chaining, it can still read worse in some cases like:
check io.Copy(w, check newReader(foo))
rather than:
io.Copy(w, newReader(foo)?)?
but now we would have:
try(io.Copy(w, try(newReader(foo))))
which I think it's clearly the worse of the three, as it's not even obvious anymore which is the main function being called.
So the gist of my comment is that all three reasons cited in the gophercon proposal for not using ? do not apply to this try proposal; ? is concise, very readable, it does not obscure the statement structure (with its internal function call hierarchy), and it is chainable. It removes even more clutter from the view, while not obscuring the control flow more than the proposed try() already does. Reacted by Travis Bischel, Matt Layher, robin, Luca Marques, Carlos (Goodwine), Patrick Stephen, jack, Ketan Parmar, Xargin, Aurélien Rainone and 152 more Reacted by Dominik Honnef, Craig Jellick, Beoran, Steven Santos Erenst, Jamie Hall, Peter Bourgon, Gabriel Adumitrachioaiei, lucy, Helmut Neemann, Bruno Silva and 18 more Reacted by ghoslin01 jimmyfrasche commented on Jun 4, 2019 To clarify:
Does
func f() (n int, err error) {
n = 7
try(errors.New("x"))
// ...
}
return (0, "x") or (7, "x")? I'd assume the latter.
Does the error return have to be named in the case where there's no decoration or handling (like in an internal helper function)? I'd assume not. Reacted by Jamie Hall, Denis Krivak, Filippo Valsorda, Alex, Oleg Kovalov, Ariel Mashraki, Burak Bilge Yalçınkaya, radhe, Baiyu Chen, Inada Naoki and 10 more Reacted by Manuel Valle, maru, aimuz, sravan kilaru and FutureArchitect-ichikawa2444 ianlancetaylor commented on Jun 5, 2019 Your example returns 7, errors.New("x"). This should be clear in the full doc that will soon be submitted (https://golang.org/cl/180557).
The error result parameter does not need to be named in order to use try. It only needs to be named if the function needs to refer to it in a deferred function or elsewhere. Reacted by jimmyfrasche, Tony Bai, Jamie Hall, Ahmed W., maru, udhos, iurii, Leigh, Ryan Avella, Inada Naoki and 2 more dominikh commented on Jun 5, 2019 I am really unhappy with a built-in function affecting control flow of the caller. This is very unintuitive and a first for Go. I appreciate the impossibility of adding new keywords in Go 1, but working around that issue with magic built-in functions just seems wrong to me. It's worsened by the fact that built-ins can be shadowed, which drastically changes the way try(foo) behaves. Shadowing of other built-ins doesn't have results as unpredictable as control flow changing. It makes reading snippets of code without all of the context much harder.
I don't like the way postfix ? looks, but I think it still beats try(). As such, I agree with @rasky .
Edit: Well, I managed to completely forget that panic exists and isn't a keyword. Reacted by Matt Layher, Aofei Sheng, Ahmed W., Roger Peppe, Will Shaw and Yash Diniz Reacted by Fareed Dudhia, timothyj-splunk, Staffan Selander, Juliano Fantozzi, Arnie97, Yash Diniz, Markku Sukanen, 桜火 and Ruby H Reacted by Bryan C. Mills and Staffan Selander griesemer commented on Jun 5, 2019 ContributorAuthor More actions The detailed proposal is now here (pending formatting improvements, to come shortly) and will hopefully answer a lot of questions. Reacted by Dmitri Shuralyov and lucy griesemer commented on Jun 5, 2019 ContributorAuthor More actions @dominikh The detailed proposal discusses this at length, but please note that panic and recover are two built-ins that affect control flow as well. Reacted by Dominik Honnef, jimmyfrasche, Jason Moiron, Tony Bai, Denis Krivak, Chandler Mayo, Dmitri Shuralyov, lucy, Saeed Madadi, Hongliang Zhou and 3 more Reacted by Al Korgun nictuku commented on Jun 5, 2019 One clarification / suggestion for improvement:
if the last argument supplied to try, of type error, is not nil, the enclosing function’s error result variable (...) is set to that non-nil error value before the enclosing function returns
Could this instead say is set to that non-nil error value and the enclosing function returns? (s/before/and)
On first reading, before the enclosing function returns seemed like it would eventually set the error value at some point in the future right before the function returned - possibly in a later line. The correct interpretation is that try may cause the current function to return. That's a surprising behavior for the current language, so a clearer text would be welcomed. Reacted by Bryan C. Mills, Nikola Kovacs and Jan purpleidea commented on Jun 5, 2019 Reacted by Marwan Sulaiman, Mike Schinkel, Baptiste Lefrancois, Ben Davies, Tomas Dohnalek, rkaaine, Jason Connell, Denis, Artem Yarmoliuk, Salyakhov Arthur and 7 more Reacted by Tzach Shabtay, Elia Perantoni and wren webermaster commented on Jun 5, 2019 Not sure why anyone ever would write a function like this but what would be the envisioned output for
try(foobar())
If foobar returned (error, error) Reacted by Daniel Mangum, Alex, Andre Hilsendeger, Rachid Lafriakh, Chao Gao, Vitalii Kozlovskyi, Oleku Konko, Peter, Al Korgun, Mani Gandham and 3 more Reacted by Lanre Adelowo, Noémi Ványi, Tolantop, Vladimir Balin, Señor Gus, Peter, Sebastian Chamena, Beau Hoyt, Adam and functionstackx dominikh commented on Jun 5, 2019 I retract my previous concerns about control flow and I no longer suggest using ?. I apologize for the knee-jerk response (though I'd like to point out this wouldn't have happened had the issue been filed after the full proposal was available).
I disagree with the necessity for simplified error handling, but I'm sure that is a losing battle. try as laid out in the proposal seems to be the least bad way of doing it. Reacted by jimmyfrasche, William Kennedy, Asif Jalil, Tony Bai, Jamie Hall, Sandor Szücs, Owais Lone, Dmitri Shuralyov, Anthony Olurin, Helmut Neemann and 14 more Reacted by inliquid ianlancetaylor commented on Jun 5, 2019 @webermaster Only the last error result is special for the expression passed to try, as described in the proposal doc. akyoto commented on Jun 5, 2019 Like @dominikh, I also disagree with the necessity of simplified error handling.
It moves vertical complexity into horizontal complexity which is rarely a good idea.
If I absolutely had to choose between simplifying error handling proposals, though, this would be my preferred proposal. Reacted by Sandor Szücs, Owais Lone, Dmitri Shuralyov, marian kopriva, udhos, Max Russell, iurii, Christian Sturm, dchapes, Michael and 14 more Reacted by Justin Tamblyn cespare commented on Jun 5, 2019 It would be helpful if this could be accompanied (at some stage of accepted-ness) by a tool to transform Go code to use try in some subset of error-returning functions where such a transformation can be easily performed without changing semantics. Three benefits occur to me:
- When evaluating this proposal, it would allow people to quickly get a sense for how
try could be used in their codebase.
- If
try lands in a future version of Go, people will likely want to change their code to make use of it. Having a tool to automate the easy cases will help a lot.
- Having a way to quickly transform a large codebase to use
try will make it easy to examine the effects of the implementation at scale. (Correctness, performance, and code size, say.) The implementation may be simple enough to make this a negligible consideration, though.
Reacted by Aofei Sheng, Burak Varlı, Jamie Hall, Mateusz Czapliński, dzrw, Pako, Russell Hernandez Ruiz, Kaur Kuut, Bryan C. Mills, Roger Peppe and 12 more Reacted by mario-moreira and Puresoul Reacted by Mateusz Czapliński, Wilk and Artyom Pervukhin Reacted by Bryan C. Mills and Aidan Coyle NareshDen commented on Nov 2, 2019 val := try f() (err){
panic(err)
} Reacted by breakon, Tv, sylba2050, Julius von Froreich, Mehmet Esen, Ray, Matt Eagar, teamalpha5441, Ivan Smyshlyaev, Lorenzo Paoliani and 2 more myroid commented on Nov 8, 2019 I hope so:
i, err := strconv.Atoi("1")
if err {
println("ERROR")
} else {
println(i)
}
or
i, err := strconv.Atoi("1")
if err {
io.EOF:
println("EOF")
io.ErrShortWrite:
println("ErrShortWrite")
} else {
println(i)
}piotrkowalczuk commented on Nov 8, 2019 @myroid I wouldn't mind having your second example made a little bit more generic in a form of switch-else statement:
i, err := strconv.Atoi("1")
switch err != nil; err {
case io.EOF:
println("EOF")
case io.ErrShortWrite:
println("ErrShortWrite")
} else {
println(i)
}Reacted by Tv, Oleksiy Chechel, aoisensi, Pavel Macháň, محمّد, iamdimka and Garet Halliday myroid commented on Nov 8, 2019 @piotrkowalczuk Your code looks much better than mine. I think the code can be more concise.
i, err := strconv.Atoi("1")
switch err {
case io.EOF:
println("EOF")
case io.ErrShortWrite:
println("ErrShortWrite")
} else {
println(i)
}Reacted by Denis, Tv, Oleksiy Chechel, aoisensi, Pavel Macháň, Alexander Liesenfeld, محمّد, iamdimka and Garet Halliday guybrand commented on Nov 8, 2019 This does not consider the option there will be an eye of different type
There needs to be
Case err!=nil
For errors the developer did not explicitly capture
…tv42 commented on Nov 8, 2019 switch doesn't need an else, it has default.
Reacted by Tom Thorogood, Steper Lin, andig, Jun Kim, Oleksiy Chechel, Isaac Weingarten and Andrea Vouk andig commented on Jul 7, 2020 I've opened #39890 which proposes something similar to Swift's guard should address some of the concerns with this proposal:
- control flow
- locality of error handling
- readability
It has not gained much traction but might be of interest for those who commented here. flysand7 commented on Jul 5, 2021 jtlapp commented on Apr 6, 2022 #52175 proposes a variation of the try syntax that does not hide error behavior. guoliang1994 commented on Aug 17, 2022 我只是一个普通的 go 开发者,并且我也没有做很多底层的开发,主要用 go 来做web开发。从使用感觉上来讲,go 的错误处理机制真的很难用。真的很难理解为什么不用try catch?实现一套异常错误处理机制,就像大部分的语言一样。
这样用不是更好吗?(我自己使用 recover 机制实现了一个try catch)
- 所有的函数将不会有错误返回值
- 可以根据不同的异常做不同的处理
- 代码大量减少
response := NewJsonResponse(w, r)
Try(func() {
...
方法可能抛出各种异常
...
}).Catch(exception.NotLoggedIn{}, func(err error) {
response.NeedLogin()
}).Catch(exception.LoginExpired{}, func(err error) {
response.LoginExpire()
}).Catch(exception.NoPermission{}, func(err error) {
response.PermissionDenied()
}).Catch(exception.RedisBroken{}, func(err error) {
response.RedisBroken()
}).Catch(&httpErrs.HTTPError{}, func(err error) {
lego.Error("系统可能正在受到 CC 攻击, 请求来源 ", r.RemoteAddr)
response.RequestSpeedTooFast()
}).CatchAll(func(err error) {
response.SysError()
}).Finally(func() {})
英文很差,见谅~
一点猜想
try catch 大概率不会被官方支持了,golang 的错误处理机制,积重难返。如果使用 try catch 这样的机制,golang的官方包,三方包统统都要改造~ Reacted by Liloupar, tzengshinfu and Thomas ILLIET Reacted by Tv, Kiswono Prayogo, Akbar Fauzi, Gonzalo Serrano, Sandesh Gade, Luis Quiñones, Andrea Vouk, Eric Driussi, jeff, Mohammad Abdolirad and 30 more mfatihercik commented on Mar 11, 2024 Although the discussion on this issue is concluded, I'd like to introduce my library, which offers a solution to the problem we've been addressing through try proposal.
One notable question from the try design document is:
If Go had “generics”, couldn’t we implement try as a generic function?
The implementation of try demands the ability to return from the function that calls try. Without a "super return" capability, try cannot be realized in Go, even with generic functions. Moreover, try necessitates a variadic parameter list that accepts different types. The anticipation for variadic generic functions of such nature is low.
My library leverages generics to replicate try's functionality, circumventing these limitations. It introduces distinct functions for handling functions with different return counts. For instance, Check1 is designed for functions with a single return value, while Check2 caters to those with two. This approach simplify function calls, exemplified by:
x := e.Check1(strconv.Atoi(a))
I know this issue is closed but I think it wort to share my library here that addressing the issue that we trying to solve with try or catch
One of the question in the try design document is as follow:
If Go had “generics”, couldn’t we implement try as a generic function?
Implementing try requires the ability to return from the function enclosing the try call. Absent such a “super return” statement, try cannot be implemented in Go even if there were generic functions. try also requires a variadic parameter list with parameters of different types. We do not anticipate support for such variadic generic functions.
I implemented a library that using generics to achieve the same functionality of the try. The difference in here for different return type I created a separate function.e.g Check1,work with function have 1 return, Check2 work with function have two return. In this way we can simplify calling functions
Example call will be:
x := e.Check1(strconv.Atoi(a))
To handle errors, the Check function triggers a panic. Errors can be caught using a defer statement alongside named returns in HandleReturn function to capture and assign the error.
Check function "panic" the error. Now we need to catch the error via defer statement.
We can use named return and HandleReturn function to catch error and set the error.
A complete usage example is as follows:
func printSum(a, b string) (err error) {
defer e.HandleReturn(func (e error){
err = e
}
x := e.Check1(strconv.Atoi(a))
y := e.Check1(strconv.Atoi(a))
fmt.Println("result:", x + y)
return nil
}
Additionally, custom error handlers can be used with the Check function to tailor error handling or add context to errors.
Custom error handler can be used as follow:
func printSum(a, b string) (err error) {
defer e.HandleReturn(func (e error){
err = e
}
convertionError:= func (err error) error {
return fmt.Errorf("failed to convert to int: %w", err)
}
x := e.Check1W(strconv.Atoi(a)).With(convertionError)
y := e.Check1W(strconv.Atoi(a)).With(convertionError)
fmt.Println("result:", x + y)
return nil
}
For more detailed examples and to explore the library further, please visit: https://github.com/mfatihercik/errless. Reacted by Chillance and Ashish Jacob Sam Reacted by mathew, Kaedys, Tv, Brendan MacDonell and wren zeroidentidad commented on Aug 9, 2024 If it is a closed issue, why can it still be commented? There are a lot of comments over the years ianlancetaylor commented on Aug 9, 2024 People can still discuss the idea even though we aren't going to adopt it. Reacted by フ乇丂ひ丂, J. Kitajima and Ivan Uhalin Reacted by フ乇丂ひ丂 flysand7 commented on Aug 10, 2024 Reacted by NobodySpecial, フ乇丂ひ丂, Big Phil, figuerom16, Mihai Todor, Giau Tran Minh and bang-tim Reacted by Tv and Kanwaljit Singh Reacted by NobodySpecial, Giau Tran Minh, Joppe Koers, bz2021, Saman Yousefisohi and J. Kitajima locked as resolved and limited conversation to collaborators on Apr 15, 2025
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|