CodeGym /Các khóa học /Go SELF /Errors at the boundaries — domain errors → CLI/HTTP forma...

Errors at the boundaries — domain errors → CLI/HTTP format

Go SELF
Mức độ, Bài học
Có sẵn

1. Application boundary: where an error becomes “human”

Neu ban tung thay mot chuong trinh tu hao in ra cho nguoi dung panic: runtime error: invalid memory address, thi ban hieu: “giao dien loi cho nguoi dung” co the… rat trung thuc. Nhung chung ta can mot loai trung thuc khac: ben trong code, chung ta muon nguyen nhan chinh xac nhat co the, con ben ngoai — mot thong diep ro rang va on dinh. Day chinh la noi ma “the gioi ben trong” gap “the gioi ben ngoai”, va no duoc goi la ranh gioi.

Tai ranh gioi, toi se hieu la bat ky lop nao giao tiep voi the gioi ben ngoai: CLI (dong lenh), HTTP API, doi khi UI, doi khi import/export tap tin. Cac lop ben trong (domain/app) khong nen biet chung ta giao tiep voi nguoi dung nhu the nao. Neu khong, domain se bat dau in ra console, con cac scenario se bat dau xu ly HTTP status — va kien truc se bien thanh mon salad.

Hay tuong tuong ung dung hoc tap cua chung ta: mot todo manager nho. Ben trong co mo hinh domain Task, cac scenario Add/Get, adapter luu tru (tam thoi in-memory), va mot “cua vao” CLI rat don gian. Hom nay chung ta se hoc cach de loi di qua cac lop mot cach gon gang: y nghia duoc giu nguyen, con hinh thuc chi thay doi tai ranh gioi.

2. Domain errors: meaning is more important than text

Khi noi ve “loi domain”, thong thuong chung ta khong co y “co cai gi do bi hong”, ma la “da xay ra mot trang thai bi cam xet theo quan diem cua mien nghiep vu”. Vi du, mot task khong the co tieu de trong. Day khong phai la van de cua console hay HTTP — day la quy tac cua the gioi todo cua chung ta.

Quan trong la phai giu trong dau mot y tuong: re-branch theo loi phai dua tren y nghia, khong phai dua tren chuoi. Chuoi la thu nguoi ta doc. Con code phai dua vao cac gia tri co the phan biet: sentinel errors hoac typed errors va cac kiem tra qua errors.Is/errors.As. Trong Go, dieu nay duoc ho tro truc tiep boi errors.Is va errors.As, nhung ham nay co the “nhin thay” loi ngay ca ben trong mot chuoi wrapper (error chain).

Sentinel errors trong domain

Hay bat dau voi dieu don gian: mot vai loi “marker” trong domain.

// domain/errors.go
package domain

import "errors"

var ErrEmptyTitle = errors.New("empty title")
var ErrNotFound = errors.New("not found")

ErrEmptyTitle va ErrNotFound khong phai la “thong diep cho nguoi dung”, ma la dinh danh cua y nghia: “tieu de trong”, “khong tim thay doi tuong”. Ban than chuoi text cua no cung quan trong, nhung nhiem vu cua no la huu ich cho debug va log.

Typed validation error

Khi so luong quy tac tang len, chung ta muon khong chi noi “validation that bai”, ma con phai kem chi tiet: truong nao, sai nhu the nao. Day la truong hop dien hinh cho typed error.

// domain/validation.go
package domain

type ValidationError struct {
	Fields map[string]string
}

func (e *ValidationError) Error() string {
	return "validation failed"
}

O day Fields la cau truc du lieu cho code, con Error() la mot chuoi ngan gon cho con nguoi. Dung, no rat nham chan — va do la binh thuong: chung ta khong muon xay UI tu Error().

Va dung, day la truong hop sau nay tai boundary (CLI/HTTP) chung ta se lay Fields thong qua errors.As.

Invariants: create an entity or return an error

Domain la noi chung ta giu cac invariant. Tuc la chung ta hoac tao ra mot Task hop le, hoac noi thang “khong duoc”.

Trong ung dung todo cua chung ta, hay de Task duoc tao thong qua constructor:

// domain/task.go
package domain

type Task struct {
	ID    int
	Title string
	Done  bool
}

func NewTask(id int, title string) (Task, error) {
	if title == "" {
		return Task{}, ErrEmptyTitle
	}
	return Task{ID: id, Title: title, Done: false}, nil
}

Hay chu y mot style quan trong: chung ta tra ve zero value (Task{}) kem voi loi. Khong co bat ky doi tuong nao bi “lap rap nua vai”. Dieu nay lam cho code o cac lop tren de hon: neu err != nil, khong the dung object do — het.

Neu quy tac nhieu hon, chung ta co the tra ve *ValidationError voi cac truong:

// domain/task.go (phuong an neu muon co truong)
package domain

func NewTask(id int, title string) (Task, error) {
	fields := make(map[string]string)
	if title == "" {
		fields["title"] = "must not be empty"
	}
	if len(fields) > 0 {
		return Task{}, &ValidationError{Fields: fields}
	}
	return Task{ID: id, Title: title, Done: false}, nil
}

Phuong an nay dac biet huu ich cho HTTP API trong tuong lai, nhung ngay luc nay cung rat co loi cho CLI: ban co the cho nguoi dung thay chinh xac dieu ho nhap sai.

3. Errors across layers: add context, keep meaning

Bay gio den lop scenario (app) — lop “dieu phoi” cac buoc: lay ID, tao task, luu lai. Tai day rat de mac hai loi dien hinh: hoac mat context (“no roi o dau?”), hoac mat y nghia (“tai sao no loi?”). Muc tieu cua chung ta la giu ca hai.

Go truc tiep thuc day chung ta den wrapping qua %w: nhu vay loi van co the “boi ra” duoc cho errors.Is/errors.As.

Dependency interface is declared by app, not by the adapter

Scenario can khong can biet loai storage nao dang dung (memory, file, database), nen no nhan vao mot interface.

// app/store.go
package app

import (
	"context"

	"example.com/todoapp/domain"
)

type TaskStore interface {
	NextID(ctx context.Context) (int, error)
	Save(ctx context.Context, t domain.Task) error
}

Task add scenario with wrapping

// app/add.go
package app

import (
	"context"
	"fmt"

	"example.com/todoapp/domain"
)

func AddTask(ctx context.Context, store TaskStore, title string) (domain.Task, error) {
	id, err := store.NextID(ctx)
	if err != nil {
		return domain.Task{}, fmt.Errorf("next id: %w", err)
	}

	t, err := domain.NewTask(id, title)
	if err != nil {
		return domain.Task{}, err
	}

	if err := store.Save(ctx, t); err != nil {
		return domain.Task{}, fmt.Errorf("save task: %w", err)
	}
	return t, nil
}

O day co mot chut tri hoc.

Chung ta wrap cac loi cua dependency (NextID, Save) — vi tu phia tren, can biet o buoc nao da loi la co ich.

Chung ta khong bat buoc wrap cac loi domain (vi du ErrEmptyTitle): chung da la “cap cua chung ta” roi. Nhung doi khi wrap cung duoc — neu ban giu duoc y nghia qua %w va khong bien chuoi thanh hop dong.

Wrapping is part of the API decision

Va day la diem tinh te. Wrapping lam cho loi “nhin thay duoc” doi voi code o tren: errors.Is(err, X) co the tim thay X ben trong chuoi. Dieu nay tuyet… cho toi khi ban vo tinh bat dau dua len tren cac loi noi bo cua adapter (vi du, sql.ErrNoRows), tuc la ban dang cam ket voi the gioi: “chung toi se luon su dung dung database nay va dung loi nay”.

Trong cac phan giai thich chinh thuc ve loi trong Go, cach noi thuong rat truc dien: neu ban wrap loi cua nguoi khac va cho code o tren co the dua vao no qua unwrap, ban da bien no thanh mot phan cua API — va sau do ban se kho thay doi implementation hon.

Voi ngay hoc cua chung ta, dieu nay co nghia la: cac loi domain co the tro thanh mot phan cua contract, con cac loi cua cong nghe cu the — nen duoc “dich” sang loi domain (hoac loi cua layer), de chi tiet ben trong khong bi lo ra ngoai.

4. Adapter: translating technical problems into meaningful ones

Adapter la noi hien thuc ky thuat gap domain cua chung ta. Ke ca khi ngay hom nay chung ta chi co in-memory storage don gian, phong cach van nen duoc dat nhu nhau cho cac storage nghiem tuc hon: adapter co the tra ve domain.ErrNotFound neu khong co ban ghi.

Hay tao mot memstore toi thieu:

// adapters/memstore/store.go
package memstore

import (
	"context"

	"example.com/todoapp/domain"
)

type Store struct {
	next int
	data map[int]domain.Task
}

func New() *Store {
	return &Store{next: 1, data: make(map[int]domain.Task)}
}

Va bay gio la cac method. Hay giu chung don gian, khong “lam mau”.

// adapters/memstore/save.go
package memstore

import (
	"context"

	"example.com/todoapp/domain"
)

func (s *Store) NextID(ctx context.Context) (int, error) {
	id := s.next
	s.next++
	return id, nil
}

func (s *Store) Save(ctx context.Context, t domain.Task) error {
	s.data[t.ID] = t
	return nil
}

Con day la vi du doc voi “not found”:

// adapters/memstore/get.go
package memstore

import (
	"context"

	"example.com/todoapp/domain"
)

func (s *Store) ByID(ctx context.Context, id int) (domain.Task, error) {
	t, ok := s.data[id]
	if !ok {
		return domain.Task{}, domain.ErrNotFound
	}
	return t, nil
}

O day adapter khong noi “map key missing” (vi day khong he la y nghia cua domain). No noi “khong tim thay” bang ngon ngu cua domain.

5. CLI boundary: message and return code

CLI la mot boundary dac biet. No thich tinh cu the: viet gi cho nguoi dung, viet vao dau (stdout hay stderr), va tra ve exit code nao. Dong thoi, CLI khong nen phan tich “noi tu” cua ung dung bang chuoi loi — chi phan tich theo y nghia qua errors.Is/errors.As.

Mot trong nhung ky thuat huu ich nhat trong Go (va noi chung trong cuoc song) la tach format loi ra mot ham rieng: WriteError(...) hoac RenderError(...). Nhu vay main se ngan gon, con logic khong bi trai rong khap project.

Mini table of mappings

Hay dat ra mot quy uoc. Tam thoi chua can standard hoa phuc tap, chi can mot muc toi thieu hop ly.

Error meaning What to show to the user Where to print Exit code
validation “Invalid input: …” stderr 2
not found “Not found: …” stderr 1
other “Internal error” stderr 1

Dung, bang nay se con phat trien, nhung chinh y tuong moi quan trong hon: boundary quyet dinh hinh thuc, con cac lop ben trong quyet dinh y nghia.

Render errors for CLI via errors.Is/As

// boundary/cli/errors.go
package cli

import (
	"errors"
	"fmt"
	"io"

	"example.com/todoapp/domain"
)

func WriteError(w io.Writer, err error) int {
	var ve *domain.ValidationError
	if errors.As(err, &ve) {
		fmt.Fprintln(w, "invalid input:", ve.Fields) // invalid input: map[title:must not be empty]
		return 2
	}
	if errors.Is(err, domain.ErrNotFound) {
		fmt.Fprintln(w, "not found") // not found
		return 1
	}
	fmt.Fprintln(w, "internal error") // internal error
	return 1
}

Hay chu y errors.As(err, &ve). O day chung ta truyen dia chi cua bien de ham co the “ghi loi da tim thay” vao ben trong no — day la contract chuan cua errors.As.

Va them mot chi tiet nua: chung ta khong in err.Error() cho nguoi dung trong cac truong hop “khac”. Tai sao? Vi trong err co the co bat cu thu gi: chi tiet storage, duong dan tap tin, goi y noi bo cho developer. Nguoi dung thuong khong vui ve dieu do, va doi khi con khong an toan.

main.go example: minimal skeleton

Hay tao mot CLI cuc ky don gian khong dung flag (chung ta se phan tich rieng o phan khac cua khoa hoc). Goi lenh co the la: todoadd <title>.

// cmd/todo/main.go
package main

import (
	"context"
	"fmt"
	"os"

	"example.com/todoapp/adapters/memstore"
	"example.com/todoapp/app"
	"example.com/todoapp/boundary/cli"
)

func main() {
	store := memstore.New()

	title := ""
	if len(os.Args) >= 2 {
		title = os.Args[1]
	}

	t, err := app.AddTask(context.Background(), store, title)
	if err != nil {
		code := cli.WriteError(os.Stderr, err)
		os.Exit(code)
	}

	fmt.Println("added:", t.Title) // added: buy milk
}

O day dieu quan trong la cau truc tu duy: main khong nen “nghi” ve cac kieu loi. No uy quyen viec do cho boundary cli.

6. HTTP boundary: same meaning, different form

Voi HTTP, cau chuyen cung y nhu vay, chi la hinh thuc khac. Ben nhan o do thuong khong phai la nguoi, ma la script hoac frontend client. No can hieu on dinh: day la loi validation? not found? internal? Vi vay boundary HTTP thuong tra ve loi “co cau truc”: status code + JSON (hoac toi thieu la error code).

Hom nay chung ta khong xay HTTP server, nhung chung ta co the (va nen) chuan bi mot ham chuyen doi loi thanh HTTP response. Sau nay no se duoc dung trong cac handler.

Nhan tien, tach xu ly loi thanh mot diem duy nhat cho HTTP la mot practice binh thuong trong Go: thay vi lap lai if err != nil { ... } trong moi handler, nguoi ta tao mot lop chung, nhan vao error va quyet dinh can gui gi ra ngoai.

Error response structure

// boundary/httpx/errors.go
package httpx

type ErrorResponse struct {
	Status  int
	Code    string
	Message string
	Fields  map[string]string
}

Day khong phai net/http va cung khong phai JSON thuc su — chi la mot cau truc de sau nay de ma encode. Y tuong quan trong: Message — cho the gioi ben ngoai, Code — cho may, Fields — cho validation.

Mapping errors to HTTP responses

// boundary/httpx/map.go
package httpx

import (
	"errors"

	"example.com/todoapp/domain"
)

func ToErrorResponse(err error) ErrorResponse {
	var ve *domain.ValidationError
	if errors.As(err, &ve) {
		return ErrorResponse{Status: 400, Code: "validation", Message: "bad request", Fields: ve.Fields}
	}
	if errors.Is(err, domain.ErrNotFound) {
		return ErrorResponse{Status: 404, Code: "not_found", Message: "not found"}
	}
	return ErrorResponse{Status: 500, Code: "internal", Message: "internal error"}
}

Chung ta lai su dung errors.As va errors.Is. Tuc la “dong co da nang” cua chung ta la cac loi co y nghia cua domain va kiem tra qua chuoi.

Neu sau nay trong app layer chung ta wrap loi nhu fmt.Errorf("get task: %w", domain.ErrNotFound), boundary van nhan dien duoc ErrNotFound, vi errors.Is di qua chuoi.

What to pass upward, and what is better to hide

Rat muon lam the nay: “neu os.Open tra ve loi — chi can wrap bang %w va dua len tren”. Doi khi nhu vay la dung. Nhung doi khi quyet dinh nay vo tinh cam ket len ngoai cac chi tiet implementation.

Toi dinh nghia mot cach thuc te: wrapping khong chi la “de dep hon”, ma wrapping la cach noi voi code cap tren: “ban co the dua vao dieu nay”. Neu ban cho phep unwrap mot loi cua nguoi khac, ban gan nhu da ky ten rang no la mot phan cua API cua ban, va ban se khong the thay doi cong nghe mot cach em ai.

Voi ung dung todo cua chung ta, dieu nay co nghia nhu sau.

Neu adapter “khong tim thay ban ghi”, no phai tra ve domain.ErrNotFound, khong phai “mot loi cua map” va cung khong phai “mot loi cua database”. Luc do domain.ErrNotFound tro thanh chinh cai neo y nghia ma ca CLI lan HTTP deu hieu.

Neu adapter gap mot loi ky thuat bat ngo (vi du, “khong mo duoc file”), app-layer co the wrap no kem context ("save task: %w"), con boundary co the hien thi "internal error" cho nguoi dung, nhung log (hoac viec in err cho developer) van chua chuoi nguyen nhan.

Va day la noi can bang chinh xuat hien: voi nguoi lam debug, viec thay tat ca rat huu ich; con voi nguoi dung, chi can dieu de hieu. Day chinh la y nghia cua “errors at the boundaries”.

7. Typical mistakes

Mistake #1: compare errors by string (err.Error() == "not found").
Nghe co ve nhanh, nhung no bien chuoi thanh hop dong, ma chuoi gan nhu luc nao cung thay doi: ban them context, sua cach dien dat, localize thong diep — va dot nhien logic re-branch se bi hong. Thay vao do, hay dung errors.Is cho sentinel errors va errors.As cho typed errors, de re-branch theo y nghia.

Mistake #2: wrapping without %w where meaning matters.
Neu ban viet fmt.Errorf("save task: %v", err), thi ve mat con nguoi moi voi, nhung voi chuong trinh thi chuoi nguyen nhan da bi mat: errors.Is/errors.As khong con tim thay loi domain ban dau nua. Neu ban ky vong boundary nhan dien duoc y nghia — hay dung %w.

Mistake #3: leaking implementation details through wrapping.
Doi khi developer lam “dung bai hoc”: noi dau cung %w, tat ca deu “chuan”. Nhung roi phat hien lop tren bat dau kiem tra errors.Is(err, sql.ErrNoRows) hoac mot loi dac thu cua thu vien nao do. Dieu nay gan code cua ban vao mot cong nghe cu the va lam refactor tro nen dau don. Noi nao cong nghe chi la chi tiet noi bo, tot hon het la “dich” loi sang domain (vi du, domain.ErrNotFound) va chi dua cai do ra ngoai.

Mistake #4: the domain prints errors or chooses the exit code.
Day la mot trong nhung tho quen pha hoai nhat: “toi chi fmt.Println o day de nhin thay”. Sau vai tuan, domain bat dau phu thuoc vao fmt, scenario phu thuoc vao os.Exit, va test tro nen rat buon. Hay giu mot quy tac sat thep: domain va app tra ve error, con boundary quyet dinh se lam gi voi no va no se hien thi nhu the nao cho nguoi dung.

Mistake #5: the boundary shows err.Error() to the user for every error.
Ben trong loi co the chua qua nhieu thong tin thua: duong dan noi bo, chi tiet ky thuat, doi khi ca mot phan cau hinh. Dieu do khong giup nguoi dung, va doi khi con gay hai. Phong cach dung: tai boundary, ban nhan dien y nghia (validation/notfound/internal) va hien thi thong diep on dinh, con loi day du de lai cho log/chan doan cua developer.

1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Lỗi không tìm thấy
Lỗi không tìm thấy
1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Lỗi xác thực
Lỗi xác thực
1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Bọc ý nghĩa
Bọc ý nghĩa
1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Phản hồi không dùng HTTP
Phản hồi không dùng HTTP
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION