Example 1
Input
{"productId":7,"quantity":2,"note":"Giao giờ hành chính"}Expected output
OK 7 x2 "Giao giờ hành chính"
Example 2
Input
{"productId":7,"quantity":0}Expected output
ValidationError [quantity] quantity phải là số nguyên từ 1 đến 100 | Error=true | Validation=true | cause=-
Example 3
Input
{oopsExpected output
ValidationError [body] JSON không hợp lệ | Error=true | Validation=true | cause=SyntaxError
5 hidden tests · Limit 2 s · 256 MB
Viết class ValidationError và hàm parseOrder(text).
class ValidationError extends Error
constructor(field, message, options) — truyền message và options (để hỗ trợ cause) lên lớp cha.name là "ValidationError", field là tên trường bị lỗi.parseOrder(text) nhận chuỗi JSON, kiểm tra theo thứ tự và ném ValidationError ở lỗi đầu tiên gặp phải:
| Điều kiện | field | message |
|---|---|---|
text không phải JSON hợp lệ (giữ lỗi gốc trong cause) | body | JSON không hợp lệ |
Giá trị không phải object (null, mảng, chuỗi, số…) | body | Body phải là object |
productId không phải số nguyên dương | productId | productId phải là số nguyên dương |
quantity không phải số nguyên từ 1 đến 100 | quantity | quantity phải là số nguyên từ 1 đến 100 |
Hợp lệ thì trả về { productId, quantity, note }, với note mặc định "" khi thiếu hoặc null.
Ví dụ
parseOrder('{"productId":7,"quantity":2}'); // { productId: 7, quantity: 2, note: "" }
try {
parseOrder("{oops");
} catch (e) {
e.name; // "ValidationError"
e.field; // "body"
e.cause.name; // "SyntaxError"
}class ValidationError extends Error {
// constructor(field, message, options)
}
function parseOrder(text) {
// ...
}
Comments