本文通过一个完整的例子,介绍如何在 gorilla/mux 框架下设计合理的 API 错误码。
我们将会使用 rk-boot 来启动 gorilla/mux 微服务。
请访问如下地址获取完整教程:
一个合理的 RPC 错误,需要考虑如下几个方面。
{
"error":{
"code":500,
"status":"Internal Server Error",
"message":"Panic manually!",
"details":[]
}
}
go get github.com/rookie-ninja/rk-boot/mux
通过 rk-boot ,用户可以轻松搭建 gorilla/mux 框架微服务,rk-boot 集成了 Panic 捕捉以及标准错误类型。
boot.yaml 文件描述了 gorilla/mux 框架启动的元信息,rk-boot 通过读取 boot.yaml 来启动 gorilla/mux。
---
mux:
- name: greeter
port: 8080
enabled: true
让 /v1/greeter 返回一个错误。
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"github.com/rookie-ninja/rk-boot"
"github.com/rookie-ninja/rk-boot/mux"
"github.com/rookie-ninja/rk-common/error"
"github.com/rookie-ninja/rk-mux/interceptor"
"net/http"
)
func main() {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Register handler
entry := rkbootmux.GetMuxEntry("greeter")
entry.Router.NewRoute().Methods(http.MethodGet).Path("/v1/greeter").HandlerFunc(Greeter)
// Bootstrap
boot.Bootstrap(context.TODO())
boot.WaitForShutdownSig(context.TODO())
}
func Greeter(writer http.ResponseWriter, request *http.Request) {
err := rkerror.New(
rkerror.WithHttpCode(http.StatusAlreadyReported),
rkerror.WithMessage("Trigger manually!"),
rkerror.WithDetails("This is detail.", false, -1, 0.1))
rkmuxinter.WriteJson(writer, http.StatusAlreadyReported, err)
}
$ go run main.go
$ curl "localhost:8080/v1/greeter?name=rk-dev"
{
"error":{
"code":208,
"status":"Already Reported",
"message":"Trigger manually!",
"details":[
"This is detail.",
false,
-1,
0.1
]
}
}
我们还是以 demo 代码为例子。
在 RPC 实现中,我们试着让系统崩溃,看看 rk-boot 会如何自动捕获,并且返回何种信息给用户。
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"github.com/rookie-ninja/rk-boot"
"github.com/rookie-ninja/rk-boot/mux"
"net/http"
)
func main() {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Register handler
entry := rkbootmux.GetMuxEntry("greeter")
entry.Router.NewRoute().Methods(http.MethodGet).Path("/v1/greeter").HandlerFunc(Greeter)
// Bootstrap
boot.Bootstrap(context.TODO())
boot.WaitForShutdownSig(context.TODO())
}
func Greeter(writer http.ResponseWriter, request *http.Request) {
panic("Panic manually!")
}
$ curl "localhost:8080/v1/greeter?name=rk-dev"
{
"error":{
"code":500,
"status":"Internal Server Error",
"message":"Panic manually!",
"details":[]
}
}
rk-boot 里对于错误的处理,实现于 rk-common/error 中。
请参考:rk-demo 获取更多例子。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。