자바스크립트에서 JSON 예외 처리 예시

외부 세계로부터 다음과 같은 제품 정보 JSON이 들어온다고 가정해 봅시다:

javascriptlet json = '{"product": "apple", "price": 1000, "amount": 5}';
let product = JSON.parse(json);
alert(product.price * product.amount);

JSON.parse 메서드는 JSON이 올바르지 않을 경우 예외를 발생시킨다는 것을 이미 알고 계실 것입니다. 이 예외를 잡아봅시다:

javascripttry {
  let json = '{"product": "apple", "price": 1000, "amount": 5}';
  let product = JSON.parse(json);
  alert(product.price * product.amount);
} catch (error) {
  // 예외에 대한 대응
}

그러나 JSON 자체는 올바르지만 필요한 필드가 없을 수도 있습니다. 예를 들어, 가격 필드가 없는 경우입니다:

javascriptlet json = '{"product": "apple", "amount": 5}'; // 가격 없음

이것도 예외 상황이라고 간주하고, 이 경우 사용자 정의 예외를 발생시키도록 하겠습니다:

javascripttry {
  let json = '{"product": "apple", "amount": 5}';
  let product = JSON.parse(json);
  
  if (product.price !== undefined && product.amount !== undefined) {
    alert(product.price * product.amount);
  } else {
    throw {
      name: 'ProductCostError',
      message: '제품에 가격 또는 수량이 없습니다'
    };
  }
} catch (error) {
  // 예외에 대한 대응
}

이제 catch 블록은 두 가지 유형의 예외를 받게 됩니다: JSON 자체가 올바르지 않아 발생하는 SyntaxError 유형의 예외, 또는 JSON은 올바르지만 우리에게 필요한 필드가 없어 발생하는 ProductCostError 유형의 예외.

catch 블록에서 이러한 예외 유형들을 구분하여 처리해 봅시다:

javascripttry {
  let json = '{"product": "apple", "amount": 5}';
  let product = JSON.parse(json);
  
  if (product.price !== undefined && product.amount !== undefined) {
    alert(product.price * product.amount);
  } else {
    throw {
      name: 'ProductCostError',
      message: '제품에 가격 또는 수량이 없습니다'
    };
  }
} catch (error) {
  if (error.name == 'SyntaxError') {
    alert('제품 JSON 형식이 올바르지 않습니다');
  } else if (error.name == 'ProductCostError') {
    alert('제품에 가격 또는 수량이 없습니다');
  }
}
Задание 1

다음과 같은 형태의 JSON이 들어온다고 가정합니다:

javascriptlet json = `[
  {
    "name": "user1",
    "age": 25,
    "salary": 1000
  },
  {
    "name": "user2",
    "age": 26,
    "salary": 2000
  },
  {
    "name": "user3",
    "age": 27,
    "salary": 3000
  }
]`;

파싱 시 이 JSON의 일반적인 유효성을 검사하고, 파싱 후 결과가 배열인지 아닌지 확인하세요. 결과가 배열이 아니라면 예외를 발생시키세요.