Bài tập: Phân cấp lỗi HTTP với extends
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 Errorconstructor(status, message)—messagelà thông điệp lỗi (củaError), lưustatusthành thuộc tính;namelà"HttpError".toJSON()trả về object{ status, error, message }, trong đóerrorlànamecủa lỗi (đúng thứ tự khóa này).static from(err)— nếuerrđã là mộtHttpError(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ỗi404với message"Không tìm thấy " + resource;namelà"NotFoundError".class ValidationError extends HttpError—constructor(field, message)tạo lỗi400, lưu thêm thuộc tínhfield;namelà"ValidationError". Ghi đètoJSON()để có thêm khóafieldở 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.
Examples
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
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