ရိုးရိုးလေး ရှင်းပြမယ်
Error နဲ့ observability ကို ရိုးရိုးလေး ပြောရရင်
Production မှာ တစ်ခုခု မှားသွားတဲ့အခါ လူနှစ်မျိုးက error ကို မြင်ရပါတယ်။ User က 'ဘာဖြစ်လဲ၊ ဘာလုပ်ရမလဲ' ကို ရှင်းရှင်းလေး သိချင်ပြီး internal detail တွေ မမြင်သင့်ပါဘူး။ On-call engineer ကတော့ ဘယ် request၊ ဘယ် dependency၊ ဘယ် error code ဆိုတာ အသေးစိတ် သိဖို့ လိုပါတယ်။
Observability ဆိုတာ system ကို အပြင်ကနေ ကြည့်ပြီး အထဲမှာ ဘာဖြစ်နေလဲ နားလည်နိုင်စွမ်းပါ။ ရှာလို့ရတဲ့ structured log၊ နှုန်းထားတွေကို ပြတဲ့ metric နဲ့ request တစ်ခု service တွေကြား ဖြတ်သွားပုံကို ပြတဲ့ trace တို့က အဓိက အစိတ်အပိုင်း သုံးခုပါ။
Problem → Why → Solution
ပြဿနာ: 'Something broke' နဲ့ password ပါတဲ့ log
Checkout fail ဖြစ်တယ်လို့ customer က တိုင်ကြားပါတယ်။ Log ထဲမှာ console.log('error', err) line ထောင်ချီ ရှိပေမဲ့ ဘယ်ဟာက ဒီ customer ရဲ့ request လဲ မသိရပါဘူး၊ request ID မပါလို့ပါ။ ပိုဆိုးတာက login error တစ်ခုက req.body တစ်ခုလုံးကို log ထုတ်ထားလို့ password တွေ log system ထဲ စာသားအတိုင်း ရောက်နေပါတယ်။ Customer ကိုယ်တိုင်ကလည်း browser ထဲမှာ database host နာမည်ပါတဲ့ stack trace ကို မြင်နေရပါတယ်။
app.post('/login', async (req, res) => {
try {
await auth.login(req.body.email, req.body.password);
res.sendStatus(204);
} catch (err) {
console.log('login error', err, req.body); // free text + the password
res.status(500).send(err.stack); // internals sent to the browser
}
});ဘာကြောင့် ဒီ log တွေ အသုံးမဝင်ပြီး အန္တရာယ်ရှိတာလဲ
Free-text log ကို filter ဒါမှမဟုတ် count လုပ်လို့ မရပါဘူး၊ request ID မပါရင် line တွေကို ဆက်စပ်လို့ မရပါဘူး။ Object တစ်ခုလုံးကို dump လုပ်ရင် secret တွေ ပေါက်ကြားပြီး stack trace ကို client ဆီ ပို့ရင် attacker ကို system ရဲ့ မြေပုံ ပေးလိုက်သလို ဖြစ်ပါတယ်။ ဝင်ပေါက်တစ်ခုစီမှာ error ကို classify လုပ်ပြီး audience နှစ်မျိုးအတွက် သီးခြား output ထုတ်ရပါမယ်။
Core concept: classify လုပ်၊ context ထည့်၊ audience နှစ်မျိုးအတွက် ထုတ်
Error တွေကို အုပ်စုနှစ်ခု ခွဲပါ။ Operational error တွေက ကြိုမြင်နိုင်ပါတယ်: order မရှိတာ၊ validation fail တာ၊ database ခဏ မရတာ။ Programmer error တွေကတော့ bug ပါ: undefined ရဲ့ property ကို ဖတ်တာလိုမျိုး။ Error ကို ဖန်တီးတဲ့နေရာမှာ status၊ machine-readable code (ORDER_NOT_FOUND) နဲ့ expose flag ပါတဲ့ AppError class ကို သုံးပါ။ Expose true ဖြစ်မှ message ကို client ဆီ ပို့ပြီး ကျန်တာ အားလုံးက generic 500 ဖြစ်ပါတယ်။ Error ကို wrap လုပ်တဲ့အခါ new AppError(message, { cause }) နဲ့ မူလ error ကို ထိန်းထားပါ။
Log တွေကို JSON line တစ်ကြောင်းစီ ထုတ်ပါ: level၊ event နာမည်၊ requestId နဲ့ field တွေ။ ဒါမှ log platform က level=error AND code=DB_UNAVAILABLE လို query နဲ့ ရှာနိုင်ပြီး ရေတွက်နိုင်ပါတယ်။ Request ID ကို function တိုင်းကို parameter အဖြစ် လိုက်ပေးမယ့်အစား node:async_hooks ရဲ့ AsyncLocalStorage ကို သုံးပါ: requestContext.run({ requestId }, fn) ထဲက await တွေ ဘယ်လောက်ပဲ ဆင့်ဆင့်ခေါ်ခေါ် getStore() က အဲဒီ request ရဲ့ context ကို ပြန်ပေးပါတယ်။
Log ထဲ ဘာထည့်မလဲဆိုတာကိုလည်း allowlist နဲ့ ဆုံးဖြတ်ပါ။ Event နာမည်၊ ID တွေ၊ status၊ duration နဲ့ error code လို ရှာဖွေဖို့ အသုံးဝင်တဲ့ field တွေကို ထည့်ပြီး password၊ token၊ cookie နဲ့ card number လို field တွေကို log ထဲ မရောက်ခင် redact လုပ်ပါ။ Log line တစ်ကြောင်းက တစ်ခုခု ဖြစ်သွားတဲ့ အချိန်မှာ 'ဘာ၊ ဘယ်သူ့ request၊ ဘာကြောင့်' ဆိုတာ ဖြေနိုင်ရပါမယ်။
| Error အမျိုးအစား | Client ရမယ့် response | Log level |
|---|---|---|
| Validation fail | 400 + ဘာမှားလဲ | warn ဒါမှမဟုတ် info |
| Record မရှိ | 404 + code | warn |
| Dependency မရ | 503 ဒါမှမဟုတ် 500 + generic | error |
| Bug (TypeError စသည်) | 500 + generic | error + stack |
Process အဆင့် error တွေက သီးခြားပါ။ Node.js မှာ ဘယ်သူမှ catch မလုပ်တဲ့ promise rejection က ပုံမှန်အားဖြင့် process ကို exit code 1 နဲ့ crash ဖြစ်စေပါတယ်။ unhandledRejection ဒါမှမဟုတ် uncaughtException listener ထည့်ရင် crash ကို ရပ်လိုက်တာ ဖြစ်ပေမဲ့ process ရဲ့ state က ယုံကြည်ရလောက်တော့ မရှိတော့ပါဘူး။ ဒါကြောင့် listener ထဲမှာ fatal log ထုတ်ပြီး graceful shutdown ကို စကာ process ကို ထွက်ခိုင်းပါ၊ process manager က အသစ်ပြန်စပါလိမ့်မယ်။
- Error ဖြစ်: AppError ဒါမှမဟုတ် bug
- Boundary မှာ classify လုပ်
- Client: code + လုံခြုံတဲ့ message
- Log: requestId + redact ထားတဲ့ detail
- Fatal ဆိုရင် shut down
Client response နဲ့ log line ကို object တစ်ခုတည်းကနေ ထုတ်ပေမဲ့ field စာရင်း မတူပါဘူး — နှစ်ခုလုံးအတွက် allowlist ကိုယ်စီ ရှိပါတယ်။
အထွေထွေ ပုံစံ
class AppError extends Error {
constructor(message, { status, code, expose, cause } = {}) {
super(message, { cause }); // then store status, code and expose
}
}
try {
return await work();
} catch (error) {
logger.error({ requestId, code: error.code, message: error.message });
return error.expose ? publicResponse(error) : genericServerError();
}Error ကို ဖန်တီးတဲ့နေရာက status နဲ့ code ကို သိပြီး boundary (route handler ဒါမှမဟုတ် error middleware) က log ထုတ်ခြင်းနဲ့ response ပြန်ခြင်းကို တစ်နေရာတည်းမှာ လုပ်ပါတယ်။
Worked example: order lookup တစ်ခုရဲ့ error လမ်းကြောင်း သုံးမျိုး
ဒီ example က request သုံးခုကို simulate လုပ်ပါတယ်: အောင်မြင်တဲ့ lookup၊ client ကို ပြောပြလို့ရတဲ့ 404 နဲ့ database ချိတ်မရလို့ ဖြစ်တဲ့ internal error။ Request တိုင်းကို AsyncLocalStorage context ထဲမှာ run လို့ log function က requestId ကို parameter မလိုဘဲ ရပါတယ်။ JSON line တွေက operator အတွက်ဖြစ်ပြီး -> line တွေက client မြင်ရမယ့် response ပါ။ တတိယ request မှာ log ထဲ cause ပါပေမဲ့ client က generic message ပဲ ရတာကို သတိထားကြည့်ပါ။
import { AsyncLocalStorage } from 'node:async_hooks';
class AppError extends Error {
constructor(message, { status = 500, code = 'INTERNAL', expose = false, cause } = {}) {
super(message, { cause });
this.name = 'AppError';
this.status = status;
this.code = code;
this.expose = expose; // may the client see this message?
}
}
const requestContext = new AsyncLocalStorage();
function log(level, event, fields = {}) {
const requestId = requestContext.getStore()?.requestId ?? null;
// A real logger also adds a timestamp; it is left out so the output is repeatable.
console.log(JSON.stringify({ level, event, requestId, ...fields }));
}
function toResponse(error) {
if (error instanceof AppError && error.expose) {
return { status: error.status, body: { error: error.code, message: error.message } };
}
return { status: 500, body: { error: 'INTERNAL', message: 'Something went wrong' } };
}
async function findOrder(id) {
if (id === 'missing') {
throw new AppError(`Order ${id} not found`, {
status: 404, code: 'ORDER_NOT_FOUND', expose: true,
});
}
if (id === 'db-down') {
const cause = new Error('connect ECONNREFUSED 10.0.0.5:5432');
throw new AppError('Order lookup failed', { code: 'DB_UNAVAILABLE', cause });
}
return { id, total: 42 };
}
async function handle(requestId, orderId) {
return requestContext.run({ requestId }, async () => {
try {
const order = await findOrder(orderId);
log('info', 'order_found', { orderId });
return { status: 200, body: order };
} catch (error) {
const response = toResponse(error);
log(response.status >= 500 ? 'error' : 'warn', 'request_failed', {
status: response.status,
code: error.code,
message: error.message,
cause: error.cause?.message, // undefined fields vanish from JSON
});
return response;
}
});
}
const requests = [['req-1', 'A7'], ['req-2', 'missing'], ['req-3', 'db-down']];
for (const [requestId, orderId] of requests) {
const { status, body } = await handle(requestId, orderId);
console.log(`-> ${status} ${JSON.stringify(body)}`);
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Error with metadata
super(message, { cause });Error constructor ရဲ့ cause option က မူလ error ကို error.cause အဖြစ် ထိန်းထားပေးလို့ wrap လုပ်ပြီးနောက်တောင် ECONNREFUSED ဆိုတဲ့ အမှန်တကယ် အကြောင်းရင်း မပျောက်ပါဘူး။
- Context without parameters
const requestId = requestContext.getStore()?.requestId ?? null;getStore() က လက်ရှိ async call chain ကို စတင်ခဲ့တဲ့ run() ရဲ့ object ကို ပြန်ပေးပါတယ်။ findOrder ကို requestId ပေးစရာ မလိုပါဘူး။
- Two audiences
if (error instanceof AppError && error.expose) {Expose လုပ်ထားတဲ့ AppError မှသာ code နဲ့ message ကို client ဆီ ပို့ပါတယ်။ TypeError လို bug တွေနဲ့ expose မလုပ်ထားတဲ့ error တွေက 'Something went wrong' ပဲ ဖြစ်ပါတယ်။
- Level by severity
log(response.status >= 500 ? 'error' : 'warn', 'request_failed', {404 က client ဘက်က ပြဿနာ ဖြစ်လို့ warn ဖြစ်ပြီး 500 ကတော့ ကိုယ့်ဘက်က ပြဿနာ ဖြစ်လို့ error ပါ။ Alert တွေကို error level ပေါ်မှာပဲ ထားလေ့ ရှိပါတယ်။
- Request scope
return requestContext.run({ requestId }, async () => {Express မှာ ဒီ run() ကို middleware ထဲ ထည့်ပြီး request ID ကို header (ဥပမာ x-request-id) ကနေ ယူတာ ဒါမှမဟုတ် crypto.randomUUID() နဲ့ ဖန်တီးလေ့ ရှိပါတယ်။
{"level":"info","event":"order_found","requestId":"req-1","orderId":"A7"}
-> 200 {"id":"A7","total":42}
{"level":"warn","event":"request_failed","requestId":"req-2","status":404,"code":"ORDER_NOT_FOUND","message":"Order missing not found"}
-> 404 {"error":"ORDER_NOT_FOUND","message":"Order missing not found"}
{"level":"error","event":"request_failed","requestId":"req-3","status":500,"code":"DB_UNAVAILABLE","message":"Order lookup failed","cause":"connect ECONNREFUSED 10.0.0.5:5432"}
-> 500 {"error":"INTERNAL","message":"Something went wrong"}Process-level fatal error များ
Fatal handler တွေကို entry point ရဲ့ အပေါ်ဆုံးမှာ တစ်ကြိမ်တည်း register လုပ်ပါ။ အရေးကြီးတာက handler က process ကို ဆက် run မထားတာပါ — exit code ကို 1 လို့ သတ်မှတ်ပြီး shutdown ကို စကာ နောက်ဆုံး အာမခံချက်အဖြစ် unref လုပ်ထားတဲ့ timer နဲ့ process.exit(1) ကို ခေါ်ပါတယ်။ exitCode သတ်မှတ်ရုံနဲ့ server ပွင့်နေသရွေ့ process က မထွက်ပါဘူး။
// Register once, at the very top of the entry point.
function onFatal(kind) {
return (error) => {
console.error(JSON.stringify({
level: 'fatal', event: kind, name: error?.name, message: error?.message,
}));
process.exitCode = 1;
// Stop taking new work and shut down (lesson 21); never keep serving
// traffic as if nothing happened. The unref'd timer is a last resort.
setTimeout(() => process.exit(1), 5_000).unref();
};
}
process.on('uncaughtException', onFatal('uncaught_exception'));
process.on('unhandledRejection', onFatal('unhandled_rejection'));
console.log('fatal handlers installed:', process.listenerCount('unhandledRejection'));လက်တွေ့ project တွေမှာ
Production မှာ observability stack တစ်ခု
လက်တွေ့ project တွေမှာ console.log ကို တိုက်ရိုက် မသုံးဘဲ pino လို JSON logger ကို သုံးပါတယ်၊ redact path တွေ၊ log level နဲ့ request ID ကို built-in ထောက်ပံ့ပေးပါတယ်။ App က stdout ဆီ ရေးပြီး container platform က log တွေကို စုကာ search လုပ်လို့ရတဲ့ system ဆီ ပို့ပေးပါတယ်။
- Request ID ကို response header ထဲမှာ ပြန်ပို့ပါ၊ ဒါမှ customer support က 'ဒီ ID ကို ပို့ပေးပါ' လို့ တောင်းပြီး log line အားလုံးကို ချက်ချင်း ရှာနိုင်ပါတယ်။
- Error code အလိုက် ရေတွက်ထားတဲ့ metric (ဥပမာ DB_UNAVAILABLE တစ်မိနစ်ကို ဘယ်နှခါ) ပေါ်မှာ alert ထားပါ၊ log line တစ်ကြောင်းချင်းပေါ်မှာ မထားပါနဲ့။
- Service အများကြီး ရှိတဲ့ system တွေမှာ OpenTelemetry လို standard နဲ့ trace ID ကို service တွေကြား ပို့ပြီး request တစ်ခုရဲ့ ခရီးစဉ် တစ်ခုလုံးကို မြင်နိုင်ပါတယ်။
အမှားများ
Error နဲ့ logging မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ
err.message ဒါမှမဟုတ် stack ကို client ဆီ ပို့ခြင်း
Database driver ရဲ့ message ထဲမှာ host နာမည်၊ table နာမည်၊ တစ်ခါတစ်ရံ query အပိုင်းအစ ပါပါတယ်။ Client ဆီ expose လုပ်ဖို့ ရည်ရွယ်ပြီး ဖန်တီးထားတဲ့ AppError ရဲ့ message ကိုပဲ ပို့ပြီး ကျန်တာကို generic message နဲ့ အစားထိုးပါ။
Request body ဒါမှမဟုတ် header တစ်ခုလုံးကို log ထုတ်ခြင်း
req.body ထဲမှာ password၊ req.headers ထဲမှာ authorization token နဲ့ cookie ပါပါတယ်။ Log system ကို ဝင်ခွင့်ရှိသူတိုင်းက ဒါတွေကို ဖတ်နိုင်ပြီး retention policy အရ နှစ်နဲ့ချီ သိမ်းထားနိုင်ပါတယ်။ ထုတ်မယ့် field တွေကို ရွေးပြီး secret key တွေကို redact လုပ်ပါ။
unhandledRejection ပြီးနောက် ဆက် run နေခြင်း
Handler ထဲမှာ log ထုတ်ရုံနဲ့ ပြီးပြီလို့ ယူဆရင် transaction တစ်ဝက်တစ်ပျက်၊ ပွင့်ကျန်နေတဲ့ connection တွေနဲ့ process က traffic ဆက်လက်ခံနေပါတယ်။ Log ထုတ်ပြီး shut down လုပ်ကာ process manager ကို သန့်ရှင်းတဲ့ process အသစ် စခိုင်းပါ။
Best Practices
Best practices
- Error code တွေကို ORDER_NOT_FOUND လို တည်ငြိမ်တဲ့ string အဖြစ် ထားပါ၊ message စာသားက ပြောင်းနိုင်ပေမဲ့ code ကို client နဲ့ dashboard တွေက အားကိုးပါတယ်။
- Error ကို တစ်နေရာ (boundary) မှာပဲ log ထုတ်ပါ၊ layer တိုင်းမှာ log ထုတ်ပြီး ပြန် throw လုပ်ရင် line ထပ်နေပါတယ်။
- Log ကို stdout ဆီ JSON နဲ့ ရေးပြီး file rotation နဲ့ shipping ကို platform ကို လွှဲပါ။
- Redaction ကို test တစ်ခုနဲ့ စစ်ပါ: password ပါတဲ့ object ကို log ထုတ်ပြီး output ထဲမှာ မပါကြောင်း assert လုပ်ပါ။
Mini challenge
Mini challenge: redact လုပ်တဲ့ JSON logger
status၊ code နဲ့ details ပါတဲ့ AppError class နဲ့ error တစ်ခုကို JSON line တစ်ကြောင်းအဖြစ် ထုတ်တဲ့ logger ကို ရေးပါ။ Logger က password၊ token၊ authorization လို key နာမည်ရှိတဲ့ field တွေကို nested object ထဲမှာပါ ရှာပြီး [REDACTED] နဲ့ အစားထိုးရပါမယ်။ Output ကို test လုပ်လို့ရအောင် clock ကို inject လုပ်လို့ရပါစေ။
- AppError မှာ status (default 500)၊ code (default INTERNAL) နဲ့ details ပါရမယ်
- redact(value) က nested object နဲ့ array တွေကို recursive စစ်ရမယ်
- Log line မှာ time၊ level၊ requestId၊ name၊ code၊ status၊ message ပါရမယ်
- createLogger({ now }) က fixed clock ကို လက်ခံရမယ်
const SECRET_KEY = /pass(word)?|token|secret|authorization|cookie|api[-_]?key/i;
class AppError extends Error {
// TODO: constructor(message, { status, code, details } = {})
}
function redact(value) {
// TODO: arrays -> map; plain objects -> copy with secret keys replaced
// TODO: primitives and null -> return unchanged
}
function createLogger(options = {}) {
// TODO: now() defaults to new Date().toISOString(); write defaults to console.log
// TODO: return { error(error, { requestId }) { ...one redacted JSON line... } }
}
// TODO: log an AppError whose details include a password and an authorization header
// TODO: log a plain TypeError and check that code and status simply disappearရလဒ်: ပထမ line မှာ password နဲ့ authorization က [REDACTED] ဖြစ်ပြီး email နဲ့ user-agent က မပြောင်းပါဘူး။ ဒုတိယ line က TypeError ဖြစ်ပြီး code နဲ့ status field မပါပါဘူး။
အရိပ်အမြွက် ကြည့်ရန်
Object.fromEntries(Object.entries(obj).map(...)) က object ကို မပြောင်းဘဲ copy အသစ် တည်ဆောက်ပေးပါတယ်။ JSON.stringify က undefined value ရှိတဲ့ field တွေကို ချန်ထားခဲ့တဲ့အတွက် TypeError ရဲ့ log line မှာ code နဲ့ status မပါတော့ပါဘူး။
အဖြေ ကြည့်ရန်
const SECRET_KEY = /pass(word)?|token|secret|authorization|cookie|api[-_]?key/i;
class AppError extends Error {
constructor(message, { status, code, details } = {}) {
super(message);
this.name = 'AppError';
this.status = status ?? 500;
this.code = code ?? 'INTERNAL';
this.details = details;
}
}
function redact(value) {
if (Array.isArray(value)) return value.map(redact);
if (value === null || typeof value !== 'object') return value;
return Object.fromEntries(
Object.entries(value).map(([key, inner]) =>
[key, SECRET_KEY.test(key) ? '[REDACTED]' : redact(inner)]),
);
}
function createLogger(options = {}) {
const now = options.now ?? (() => new Date().toISOString());
const write = options.write ?? console.log;
return {
error(error, { requestId }) {
const entry = {
time: now(),
level: 'error',
requestId,
name: error.name,
code: error.code,
status: error.status,
message: error.message,
details: error.details,
};
write(JSON.stringify(redact(entry)));
},
};
}
// A fixed clock keeps this demo's output identical on every run.
const logger = createLogger({ now: () => '2026-01-01T00:00:00.000Z' });
logger.error(new AppError('Login failed', {
status: 401,
code: 'BAD_CREDENTIALS',
details: {
email: 'mya@example.com',
password: 'hunter2',
headers: { authorization: 'Bearer abc.def', 'user-agent': 'curl/8' },
},
}), { requestId: 'req-77' });
logger.error(new TypeError("Cannot read properties of undefined (reading 'id')"), {
requestId: 'req-78',
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Error ကို status၊ code၊ expose ပါတဲ့ AppError နဲ့ classify လုပ်ပြီး expose လုပ်ထားတာကိုပဲ client ဆီ ပို့ပါ။
- Log တွေကို level၊ event၊ requestId ပါတဲ့ JSON line အဖြစ် ထုတ်ပြီး AsyncLocalStorage နဲ့ request context ကို သယ်ပါ။
- Log မထုတ်ခင် password၊ token၊ authorization လို field တွေကို redact လုပ်ပါ။
- Error ကို wrap လုပ်တဲ့အခါ { cause } နဲ့ မူလ error ကို ထိန်းထားပါ။
- unhandledRejection နဲ့ uncaughtException ပြီးရင် log ထုတ်ပြီး shut down လုပ်ပါ၊ ဆက်မ run ပါနဲ့။
Errors — Node.js