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