LoginSignup
0
0

Go言語初学者がエラーに立ち向かう方法: fmt.Printfデバッグ、エラーハンドリング

Last updated at Posted at 2024-02-24

なぜエラーになったかを考える

①直近で自分は何をやっていたかを考える!

②エラー文の内容をみる!

③文法があっているかを考える!

fmt.Printfデバッグ

fmt.Printfデバッグを使用することで、スコープ内で呼ばれているかや、変数の中身の型や値が自分の意図するものになっているかを確認することができます。

fmt.Printfデバッグの例

main.go
fmt.Printf("CustomerNameError: %v\n", customerName)
//fmt.Printf("任意の命名: %v\n", 中身を見たい変数)

複数のfmt.Printfデバッグを作成し、エラーの原因の箇所を探す。

実践例

main.go
fmt.Printf("CustomerNameError①!!!: %v\n", customerName)
row := db.QueryRow("SELECT id FROM members where name = ?",customerName)
fmt.Printf("CustomerNameError②???: %v\n", customerName)
err := row.Scan(&customerName)
fmt.Printf("CustomerNameError③***: %v\n", customerName)

出力結果

main.go
fmt.Printf("CustomerNameError①!!!: %v\n", customerName)//CustomerNameError①!!!:ひなっこ
row := db.QueryRow("SELECT id FROM members where name = ?",customerName)
fmt.Printf("CustomerNameError②???: %v\n", customerName)//CustomerNameError②???:ひなっこ
err := row.Scan(&customerName)
fmt.Printf("CustomerNameError③***: %v\n", customerName)//CustomerNameError③***: 1

上記の例では
customerName = ひなっこが入っていて欲しかったが、SELECTでレコードを取得した後のCustomerNameError③デバッグの箇所ではcustomerName = 1となり、スキャーンしたidが代入されているということがわかり、エラーが発見できた!

エラーハンドリング

main.go
c := echo.New()
type Response struct {
	Message string `json:"message"`
}

db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		c.Logger().Errorf("Database connection error: %s", err)
		res := Response{Message: "Database connection error"}
		return echo.NewHTTPError(http.StatusInternalServerError, res)
	}

echoを使用している際c.Logger().Errorfはエラーログをサーバー側で出力する

main.go
c.Logger().Errorf("Error opening file: %s", err)

エラーが返された際、Message内容をclient側で出力する
echoにはecho.NewHTTPErrorというHTTPErrorHandler型が用意されており、それを使用することでエラーが出た際にクライアント側でDatabase connection errorを出力することができる。

main.go
res := Response{Message: "Error opening file"}
		return echo.NewHTTPError(http.StatusInternalServerError, res)
  //type HTTPErrorHandler func(err error , c Context )

参考文献

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