Skip to content

Commit c9a25e2

Browse files
committed
docs: prefer string codes over integers in examples and docs
- Updated README and examples to use descriptive string identifiers (e.g., USER_CREATED, ERR_NOT_FOUND) - Updated tests and test resources to use string codes - Refined documentation to recommend strings for better self-documentation
1 parent a50a86e commit c9a25e2

8 files changed

Lines changed: 21 additions & 20 deletions

File tree

README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ default:
4646
long: Unexpected message was received and was not found in this catalog
4747
set:
4848
greeting.hello:
49-
code: 1
49+
code: GREETING_HELLO
5050
short: User created
5151
long: User {{name}} was created successfully
5252
items.count:
@@ -64,6 +64,7 @@ default:
6464
long: Se recibió un mensaje inesperado y no se encontró en el catálogo
6565
set:
6666
greeting.hello:
67+
code: GREETING_HELLO
6768
short: Usuario creado
6869
long: Usuario {{name}} fue creado correctamente
6970
items.count:
@@ -98,7 +99,7 @@ ctx := context.WithValue(context.Background(), "language", "es-AR")
9899
msg := catalog.GetMessageWithCtx(ctx, "greeting.hello", msgcat.Params{"name": "juan"})
99100
fmt.Println(msg.ShortText) // "Usuario creado"
100101
fmt.Println(msg.LongText) // "Usuario juan fue creado correctamente"
101-
fmt.Println(msg.Code) // "1" (from YAML optional code; Code is string)
102+
fmt.Println(msg.Code) // "GREETING_HELLO" (from YAML optional code; Code is string)
102103
103104
params := msgcat.Params{"count": 3, "amount": 12345.5, "when": time.Now()}
104105
err := catalog.WrapErrorWithCtx(ctx, errors.New("db timeout"), "items.count", params)
@@ -268,11 +269,11 @@ After translators fill `translate.es.yaml`, rename or copy it to `es.yaml` for r
268269
Many projects already use **error or message codes** (HTTP statuses, legacy numeric codes, string identifiers like `ERR_NOT_FOUND`). The optional **`code`** field in the catalog lets you **store that value** with each message and have it returned in `Message.Code` and `ErrorCode()` so your API can expose it unchanged.
269270

270271
- **Optional** — You can omit `code` entirely. When empty, use `Message.Key` or `ErrorKey()` as the stable identifier for clients (e.g. in JSON: `"error_code": msg.Code or msg.Key`).
271-
- **Any value** — Codes are strings. In YAML you can write `code: 404` (parsed as `"404"`) or `code: "ERR_NOT_FOUND"`. In Go use `msgcat.CodeInt(503)` or `msgcat.CodeString("ERR_MAINT")`.
272+
- **Any value** — Codes are strings. In YAML you can write `code: ERR_NOT_FOUND` or `code: "404"`. In Go use `msgcat.CodeString("ERR_MAINT")` or `msgcat.CodeInt(503)`.
272273
- **Not unique** — The catalog does not require codes to be unique. If your design uses the same code for several messages (e.g. same HTTP status for different keys), you can repeat the same `code` value.
273274
- **Your identifier** — The catalog never interprets the code; it only stores and returns it. You decide what values to use and how to expose them in your API.
274275

275-
**When to set a code:** Use it when you need a stable, project-specific value to return to clients (status codes, error enums, etc.). When you don’t, leave it unset and use the message **key** as the identifier.
276+
**When to set a code:** Use it when you need a stable, project-specific value to return to clients (status codes, error enums, etc.). Strings are generally preferred over integers as they are more descriptive (e.g., `code: ERR_ACCESS_DENIED` instead of `code: 403`). When you don’t need a separate code, leave it unset and use the message **key** as the identifier.
276277

277278
Helpers for building `RawMessage.Code` in code: `msgcat.CodeInt(503)`, `msgcat.CodeString("ERR_NOT_FOUND")`.
278279

docs/CONVERSION_PLAN.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ set:
9292
short: Hello short description
9393
long: Hello veeery long description.
9494
greeting.template:
95-
code: 1002 # optional (stored as string; see §12)
95+
code: GREETING # optional (stored as string; see §12)
9696
short: Hello template {{name}}, this is nice {{detail}}
9797
long: Hello veeery long {{name}} description. Details {{detail}}.
9898
items.count:

examples/basic/main.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ func main() {
2424
long: Message not found in catalog
2525
set:
2626
greeting.hello:
27-
code: 1
27+
code: GREETING
2828
short: Hello
2929
long: Hello, welcome.
3030
greeting.template:
31-
code: 2
31+
code: WELCOME
3232
short: Hello {{name}}, role {{role}}
3333
long: Hello {{name}}, you are {{role}}.
3434
error.gone:
35-
code: 404
35+
code: NOT_FOUND
3636
short: Not found
3737
long: Resource not found.
3838
`)

examples/load_messages/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ set:
4040
Key: "sys.maintenance",
4141
ShortTpl: "Under maintenance",
4242
LongTpl: "Back in {{minutes}} minutes.",
43-
Code: msgcat.CodeInt(503), // or msgcat.CodeString("ERR_MAINTENANCE")
43+
Code: msgcat.CodeString("ERR_MAINTENANCE"),
4444
},
4545
})
4646
if err != nil {

examples/msgdef/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ var (
3131
Key: "items.count",
3232
Short: "{{count}} items",
3333
Long: "Total: {{count}} items",
34-
Code: msgcat.CodeInt(200),
34+
Code: msgcat.CodeString("OK"),
3535
}
3636
)
3737

@@ -57,7 +57,7 @@ set:
5757
items.count:
5858
short: "{{count}} items"
5959
long: "Total: {{count}} items"
60-
code: 200
60+
code: OK
6161
`)
6262
if err := os.WriteFile(filepath.Join(dir, "en.yaml"), en, 0o600); err != nil {
6363
panic(err)

test/suites/msgcat/msgcat_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ var _ = Describe("Message Catalog", func() {
8181

8282
It("should return message code", func() {
8383
message := messageCatalog.GetMessageWithCtx(ctx.Ctx, "greeting.hello", nil)
84-
Expect(message.Code).To(Equal("1"))
84+
Expect(message.Code).To(Equal("GREETING_HELLO"))
8585
})
8686

8787
It("should set Message.Key and use Key when Code is empty for API identifier", func() {
@@ -171,15 +171,15 @@ var _ = Describe("Message Catalog", func() {
171171
castedError := err.(msgcat.Error)
172172
Expect(castedError.GetShortMessage()).To(Equal("Hola, breve descripción"))
173173
Expect(castedError.GetLongMessage()).To(Equal("Hola, descripción muy larga. Solo puedes verme en la página de detalles."))
174-
Expect(castedError.ErrorCode()).To(Equal("1"))
174+
Expect(castedError.ErrorCode()).To(Equal("GREETING_HELLO"))
175175
})
176176

177177
It("should be able to load messages from code", func() {
178178
err := messageCatalog.LoadMessages("en", []msgcat.RawMessage{{
179179
Key: "sys.9001",
180180
LongTpl: "Some long system message",
181181
ShortTpl: "Some short system message",
182-
Code: msgcat.CodeInt(9001),
182+
Code: msgcat.CodeString("SYS_ERR"),
183183
}})
184184
Expect(err).NotTo(HaveOccurred())
185185
err = messageCatalog.GetErrorWithCtx(ctx.Ctx, "sys.9001", nil)
@@ -191,7 +191,7 @@ var _ = Describe("Message Catalog", func() {
191191
Key: "sys.9001",
192192
LongTpl: "Mensagem longa de sistema",
193193
ShortTpl: "Mensagem curta de sistema",
194-
Code: msgcat.CodeInt(9001),
194+
Code: msgcat.CodeString("SYS_ERR"),
195195
}})
196196
Expect(err).NotTo(HaveOccurred())
197197

@@ -218,7 +218,7 @@ var _ = Describe("Message Catalog", func() {
218218
Key: "sys.loaded",
219219
LongTpl: "Loaded from code",
220220
ShortTpl: "Loaded from code short",
221-
Code: msgcat.CodeInt(9001),
221+
Code: msgcat.CodeString("SYS_ERR"),
222222
}})
223223
Expect(err).NotTo(HaveOccurred())
224224
Expect(customCatalog.GetMessageWithCtx(ctx.Ctx, "sys.loaded", nil).ShortText).To(Equal("Loaded from code short"))
@@ -350,7 +350,7 @@ var _ = Describe("Message Catalog", func() {
350350
Key: "sys.runtime",
351351
LongTpl: "Runtime long",
352352
ShortTpl: "Runtime short",
353-
Code: msgcat.CodeInt(9001),
353+
Code: msgcat.CodeString("SYS_ERR"),
354354
}})
355355
Expect(err).NotTo(HaveOccurred())
356356

@@ -528,7 +528,7 @@ var _ = Describe("Message Catalog", func() {
528528
Key: key,
529529
LongTpl: fmt.Sprintf("Long %s", key),
530530
ShortTpl: fmt.Sprintf("Short %s", key),
531-
Code: msgcat.CodeInt(9000 + i),
531+
Code: msgcat.CodeString(fmt.Sprintf("ERR_%d", i)),
532532
}})
533533
if err != nil {
534534
errCh <- err

test/suites/msgcat/resources/messages/en.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ default:
33
long: Unexpected error was received and was not found in catalog
44
set:
55
greeting.hello:
6-
code: 1
6+
code: GREETING_HELLO
77
short: Hello short description
88
long: Hello veeery long description. You can only see me in details page.
99
greeting.template:

test/suites/msgcat/resources/messages/es.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ default:
33
long: Se recibió un error inesperado y no se encontró en el catálogo!
44
set:
55
greeting.hello:
6-
code: 1
6+
code: GREETING_HELLO
77
short: Hola, breve descripción
88
long: Hola, descripción muy larga. Solo puedes verme en la página de detalles.
99
items.count:

0 commit comments

Comments
 (0)