Example 1
Input
notfound|đơn hàng #42 validation|email|Email không hợp lệ
Expected output
NotFoundError 404 true true true Không tìm thấy đơn hàng #42
{"status":404,"error":"NotFoundError","message":"Không tìm thấy đơn hàng #42"}
ValidationError 400 true false true Email không hợp lệ
{"status":400,"error":"ValidationError","message":"Email không hợp lệ","field":"email"}Example 2
Input
http|503|Hệ thống đang bảo trì
Expected output
HttpError 503 true false true Hệ thống đang bảo trì
{"status":503,"error":"HttpError","message":"Hệ thống đang bảo trì"}4 hidden tests · Limit 2 s · 256 MB
API của bạn cần trả lỗi về client theo một định dạng thống nhất. Hãy xây dựng một cây class lỗi kế thừa từ Error:
class HttpError extends Error
constructor(status, message) — message là thông điệp lỗi (của Error), lưu status thành thuộc tính; name là "HttpError".toJSON() trả về object { status, error, message }, trong đó error là name của lỗi (đúng thứ tự khóa này).static from(err) — nếu err đã là một HttpError (kể cả lớp con) thì trả về chính nó; ngược lại trả về new HttpError(500, "Lỗi máy chủ nội bộ").class NotFoundError extends HttpError — constructor(resource) tạo lỗi 404 với message "Không tìm thấy " + resource; name là "NotFoundError".class ValidationError extends HttpError — constructor(field, message) tạo lỗi 400, lưu thêm thuộc tính field; name là "ValidationError". Ghi đè toJSON() để có thêm khóa field ở cuối: { status, error, message, field }.Mọi lỗi tạo ra đều phải là instanceof Error và instanceof HttpError.
Ví dụ
const e = new NotFoundError("đơn hàng #42");
e.status; // 404
e.message; // "Không tìm thấy đơn hàng #42"
e instanceof HttpError; // true
JSON.stringify(e); // '{"status":404,"error":"NotFoundError","message":"Không tìm thấy đơn hàng #42"}'
JSON.stringify(new ValidationError("email", "Email không hợp lệ"));
// '{"status":400,"error":"ValidationError","message":"Email không hợp lệ","field":"email"}'
HttpError.from(e) === e; // true
HttpError.from(new TypeError("x is not a function")).status; // 500TIP
JSON.stringify tự gọi method toJSON() nếu object có. Trong lớp con, super.toJSON() cho bạn kết quả của lớp cha để mở rộng thêm.
class HttpError extends Error {
constructor(status, message) {
// gọi super, đặt name và status
}
toJSON() {}
static from(err) {}
}
class NotFoundError extends HttpError {
constructor(resource) {}
}
class ValidationError extends HttpError {
constructor(field, message) {}
toJSON() {
// tái sử dụng toJSON của lớp cha
}
}
Comments