はじめに
GoによるAPIエラーの返却について説明したい。
そもそも何をエラーとして何を返却するか
参考にさせていただいたAPIエラーの返却内容
https://qiita.com/suin/items/f7ac4de914e9f3f35884
こちらを参考にすると、code,messageは入れておくのが定石みたいですね。エラー内容がわからなくなるので当然かと思います。ほかはサービスによって異なりますね。
個人的にはどこにアクセスしたかを知れるとデバッグで助かるので、urlは欲しいと思います。
実際にコードを見てみよう
下記は上の内容を踏まえて作成した、APIエラーを返却する1例です。
return func(w http.ResponseWriter, req *http.Request){
if err != nil {
apiError, _ := json.Marshal(map[string]interface{}{
"code": http.Status...,
"message": http.StatusText...,
"url": req.URL.String()
})
w.Header().Set("Content-Type", ...)
w.WriteHeader(http.Status...)
w.Write(apiError)
} else {
...
}