github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/docs/v2/library/go-errors.md (about)

     1  ---
     2  title: Errors
     3  keywords: go-micro, framework, errors
     4  tags: [go-micro, framework, errors]
     5  sidebar: home_sidebar
     6  permalink: /go-errors
     7  summary: Error handling and errors produced by Go Micro
     8  ---
     9  
    10  Go Micro provides abstractions and types for most things that occur in a distributed system including errors. By 
    11  providing a core set of errors and the ability to define detailed error types we can consistently understand 
    12  what's going on beyond the typical Go error string.
    13  
    14  # Overview
    15  
    16  We define the following error type:
    17  
    18  ```go
    19  type Error struct {
    20      Id     string `json:"id"`
    21      Code   int32  `json:"code"`
    22      Detail string `json:"detail"`
    23      Status string `json:"status"`
    24  }
    25  ```
    26  
    27  Anywhere in the system where you're asked to return an error from a handler or receive one from a client you should assume 
    28  its either a go-micro error or that you should produce one. By default we return 
    29  [errors.InternalServerError](https://pkg.go.dev/github.com/micro/go-micro/v2/errors#InternalServerError) where somethin has 
    30  gone wrong internally and [errors.Timeout](https://pkg.go.dev/github.com/micro/go-micro/v2/errors#Timeout) where a timeout occurred.
    31  
    32  ## Usage
    33  
    34  Let's assume some error has occurred in your handler. You should then decide what kind of error to return and do the following.
    35  
    36  
    37  Assuming some data provided was invalid
    38  
    39  ```go
    40  return errors.BadRequest("com.example.srv.service", "invalid field")
    41  ```
    42  
    43  In the event an internal error occurs
    44  
    45  ```go
    46  if err != nil {
    47  	return errors.InternalServerError("com.example.srv.service", "failed to read db: %v", err.Error())
    48  }
    49  ```
    50  
    51  Now lets say you receive some error from the client
    52  
    53  ```go
    54  pbClient := pb.NewGreeterService("go.micro.srv.greeter", service.Client())
    55  rsp, err := pb.Client(context, req)
    56  if err != nil {
    57  	// parse out the error
    58  	e := errors.Parse(err.Error())
    59  
    60  	// inspect the value
    61  	if e.Code == 401 {
    62  		// unauthorised...
    63  	}
    64  }
    65  ```
    66