Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

rpc-errors.md 2.3 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # RPC Errors
  2. All service method handlers should return `nil` or errors from the
  3. `status.Status` type. Clients have direct access to the errors.
  4. Upon encountering an error, a gRPC server method handler should create a
  5. `status.Status`. In typical usage, one would use [status.New][new-status]
  6. passing in an appropriate [codes.Code][code] as well as a description of the
  7. error to produce a `status.Status`. Calling [status.Err][status-err] converts
  8. the `status.Status` type into an `error`. As a convenience method, there is also
  9. [status.Error][status-error] which obviates the conversion step. Compare:
  10. ```
  11. st := status.New(codes.NotFound, "some description")
  12. err := st.Err()
  13. // vs.
  14. err := status.Error(codes.NotFound, "some description")
  15. ```
  16. ## Adding additional details to errors
  17. In some cases, it may be necessary to add details for a particular error on the
  18. server side. The [status.WithDetails][with-details] method exists for this
  19. purpose. Clients may then read those details by first converting the plain
  20. `error` type back to a [status.Status][status] and then using
  21. [status.Details][details].
  22. ## Example
  23. The [example][example] demonstrates the API discussed above and shows how to add
  24. information about rate limits to the error message using `status.Status`.
  25. To run the example, first start the server:
  26. ```
  27. $ go run examples/rpc_errors/server/main.go
  28. ```
  29. In a separate session, run the client:
  30. ```
  31. $ go run examples/rpc_errors/client/main.go
  32. ```
  33. On the first run of the client, all is well:
  34. ```
  35. 2018/03/12 19:39:33 Greeting: Hello world
  36. ```
  37. Upon running the client a second time, the client exceeds the rate limit and
  38. receives an error with details:
  39. ```
  40. 2018/03/19 16:42:01 Quota failure: violations:<subject:"name:world" description:"Limit one greeting per person" >
  41. exit status 1
  42. ```
  43. [status]: https://godoc.org/google.golang.org/grpc/status#Status
  44. [new-status]: https://godoc.org/google.golang.org/grpc/status#New
  45. [code]: https://godoc.org/google.golang.org/grpc/codes#Code
  46. [with-details]: https://godoc.org/google.golang.org/grpc/status#Status.WithDetails
  47. [details]: https://godoc.org/google.golang.org/grpc/status#Status.Details
  48. [status-err]: https://godoc.org/google.golang.org/grpc/status#Status.Err
  49. [status-error]: https://godoc.org/google.golang.org/grpc/status#Error
  50. [example]: https://github.com/grpc/grpc-go/blob/master/examples/rpc_errors