You can define errors in protos and generate enums with protoc-gen-go.

Error in errors pacakge implements GRPCStatus() interface.

  1. {
  2. // Error code, this is consistent with grpc-status and will be convert to http-status in HTTP
  3. "code": 3,
  4. // Error message, is a human-readable message.
  5. "message": "invalid argument error",
  6. // Error details
  7. "details": [
  8. {
  9. "@type": "type.googleapis.com/google.rpc.ErrorInfo",
  10. // Error Reason, is the Error code in business logic.
  11. "reason": "custom_error",
  12. // Error domain, is the business domain.
  13. "domain": "helloworld"
  14. }
  15. ]
  16. }

Installation

  1. go install google.golang.org/protobuf/cmd/protoc-gen-go

Error Defination

api/helloworld/v1/helloworld.proto

  1. syntax = "proto3";
  2. package api.helloworld.v1;
  3. // language-specified package name
  4. option go_package = "api/helloworld/v1;v1";
  5. option java_multiple_files = true;
  6. option java_package = "helloworld.v1";
  7. option objc_class_prefix = "APIHelloworldV1";
  8. enum ErrorReason {
  9. // Do not use this default value.
  10. ERROR_REASON_UNSPECIFIED = 0;
  11. // The request is calling a disabled service for a consumer.
  12. SERVICE_DISABLED = 1;
  13. }

Error Generation

To generate code with protoc.

  1. protoc --go_out=. --go_opt=paths=source_relative api/helloworld/v1/error_reason.proto

Usage

  1. import "github.com/go-kratos/kratos/errors"
  2. import "<app>/api/helloworld/v1"
  3. func doSomething() error {
  4. return errors.BadRequest("hellworld", v1.SERVICE_DISABLED.String(), "service has been disabled")
  5. }
  6. if err := doSomething(); errors.IsBadRequest(err) {
  7. // TODO
  8. }
  9. if err := doSomething(); errors.Reason(err) == v1.SERVICE_DISABLED.String() {
  10. // TODO
  11. }