0
0

GoによるAPIエラーの返却

Posted at

はじめに

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 { 
    ...
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0