Skip to content

Commit de0fe12

Browse files
authored
Some Go design guidelines cleanup (#10153)
* Some Go design guidelines cleanup Updated Pager[T] example to break out of loop on error. Improved error handling example with real-world cases. Fixed some formatting. * feedback
1 parent c4cda69 commit de0fe12

1 file changed

Lines changed: 14 additions & 7 deletions

File tree

docs/golang/introduction.md

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,8 @@ type WidgetClientGetResponse struct {
175175
}
176176

177177
type Widget struct {
178-
Name string
179-
Color WidgetColor
178+
Name *string
179+
Color *WidgetColor
180180
}
181181

182182
func (c *WidgetClient) Get(ctx context.Context, name string, options *WidgetClientGetOptions) (WidgetClientGetResponse, error) {
@@ -235,7 +235,7 @@ Cancellation is handled via the `context.Context` paramater, which is _always_ t
235235
```go
236236
// WidgetClientGetOptions contains the optional parameters for the WidgetClient.Get method.
237237
type WidgetClientGetOptions struct {
238-
Tag *string
238+
Tag *string
239239
Length *int
240240
}
241241

@@ -296,8 +296,10 @@ pager := client.NewListPager(nil)
296296
for pager.More() {
297297
page, err := pager.NextPage(context.Background())
298298
if err != nil {
299-
// handle error...
299+
// process error and exit the loop
300+
break
300301
}
302+
// no error, enumerate widgets
301303
for _, w := range page.Value {
302304
process(w)
303305
}
@@ -432,10 +434,15 @@ In addition to service client types, Azure SDK APIs provide and use other suppor
432434
{% include requirement/SHOULD id="golang-errors-wrapping" %} wrap an error with another error if it would help in the diagnosis of the underlying failure. Expect consumers to use [error helper functions](https://blog.golang.org/go1.13-errors) like `errors.As()` and `errors.Is()`.
433435

434436
```go
435-
err := xml.Unmarshal(resp.Payload, v)
436-
if err != nil {
437-
return fmt.Errorf("unmarshalling type %s: %w", reflect.TypeOf(v).Elem().Name(), err)
437+
resp, err := client.Get(context.Background(), "widget_name", nil)
438+
if azErr := (&azcore.ResponseError{}); errors.As(err, &azErr) {
439+
// service returned an error (e.g. 404 not found)
440+
} else if authErr := (&azidentity.AuthenticationFailedError{}); errors.As(err, &authErr) {
441+
// authentication failed during the request
442+
} else if err != nil {
443+
// some other error was returned
438444
}
445+
// if there was no error then process resp
439446
```
440447

441448
{% include requirement/MUST id="golang-errors-on-request-failed" %} return the service/operation specific error type when an HTTP request fails with an unsuccessful HTTP status code as defined by the service. For operations that do not define an error type, return the HTTP response body in string format if available, else return the `Status` string on the HTTP response.

0 commit comments

Comments
 (0)