190808 bridge-course js Error

zenibako.lee
6 min readAug 8, 2019

--

정리한 내용을 라이브 디스커션에서 공유하고 동료간 질문합니다.

아래 각 에러들에 대해 블로깅으로 정리하여 함께 발표합니다.

Error 생성자는 error object를 생성합니다. error object는 런타임에러시 던져지거나(e) 작성자가 설정한 예외에 던져집니다.

에러 객체 생성

// this:
const x = Error('I was created using a function call!');
​​​​// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');

new Error(msg) 혹은 Error(msg)를 통해 변수에 저장합니다.

try {
throw new Error('Whoops!');
} catch (e) {
console.log(e.name + ': ' + e.message);
} finally {
console.log('finally i did it!') // will always get executed}

위와 같이 try{}catch(e){}를 통해 try문 내 동작을 실행, 오류 발생 시 errrorObj(e)의 이름과 message를 출력하게 할 수 있습니다.

+ finally를 이용해 무조건 실행되는 스크립트를 넣을 수 있습니다.

try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
console.log(e.name + ': ' + e.message);
} else if (e instanceof RangeError) {
console.log(e.name + ': ' + e.message);
}
// ... etc
}

에러 발생 시 부모 객체의 종류에 따른 조건식 가능.

EvalError

문자열을 자바스크립트로 실행하는 도중에 발생하는 오류.

var obj = { a: 20, b: 30 };
var propname = getPropName(); // "a" 또는 "b" 를 반환

eval( "var result = obj." + propname );

멤버프로퍼티 관련 : 위와 같이 객체의 property접근을 eval을 통해 하는 것은 오류가 발생. 코드가 실행될 때까지 접근될 객체의 프로퍼티가 알려져 있지 않은 경우 발생.

InternalError

자바스크립트 내부 문제가 발생

  1. “too many switch cases”, (swich case의 수가 너무 많음.)

2. “too many parentheses in regular expression”, (정규표현식에 너무 많은 괄호가 있음.)

3. “array initializer too large”, (배열 초기화 값이 너무 큼.)

4. “too much recursion”. (너무 많은 재귀 호출.)

RangeError

숫자 변수나 매개변수가 유효한 범위를 벗어났음을 나타내는 오류 인스턴스를 생성.

  1. 허용되지 않은 범위의 수를 포함한 아규먼트를 함수에 넘기려고 할 때
  2. Array 생성자로 허용범위를 초과한 길이의 배열 생성을 시도하려 하거나
  3. 적절하지 않은 값을 numeric method(Number.toExponential(), Number.toFixed() 또는 Number.toPrecision())에 넘기려 할 때

ReferenceError

선언된 적이 없는 변수를 참조하려고 할 때 발생합니다.

SyntaxError

JavaScript 엔진이 코드를 분석할 때 문법을 준수하지 않은 코드를 만나면 발생합니다. (가장 많이 보게 되던…)

‘)’ 가 빠지거나 더 많거나 ‘;’ 가 빠지거나 들어가거나 할 때 등등.. 오타

TypeError

함수나 연산자의 인자가, 그 함수나 연산자가 예상하던 타입과 호환되지 않을 때 TypeError 오류가 던져집니다.

null.f();

property가 없는 객체인 null에 대해 property를 호출하면서 TypeError발생.

URIError

encodeURI()decodeURI()

에서 아규먼트 범위에 맞지않는 파라미터를 입력했을 때 발생.

encodeURI()는 전달받은 주소값을 암호화.

// high-low pair ok
console.log(encodeURI('\uD800\uDFFF'));

// lone high surrogate throws "URIError: malformed URI sequence"
console.log(encodeURI('\uD800'));

// lone low surrogate throws "URIError: malformed URI sequence"
console.log(encodeURI('\uDFFF'));

그러나 surrogate which is not part of a high-low pair를 인코딩 하려고 하면 URIError 발생.

MyCustomError

try-catch의 목적은 브라우저가 에러를 기본 방식대로 처리하지 못하게 막는것이고 커스텀 에러의 목적은 일어난 이유(stack)를 제공하는것입니다.

출처: https://blog.sonim1.com/156 [Kendrick’s Blog]

class CustomError extends Error {
constructor(foo = 'bar', ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor //필드변수로 선언할 변수들? 근데 선언이 바로 들어가네요?
super(...params); //부모(Error)의 constructor();

// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}

// Custom debugging information
this.foo = foo; //this는 CustomerError로 생성된 객체?
this.date = new Date();
}
}

try {
throw new CustomError('baz', 'bazMessage');
} catch(e){
console.log(e.foo); //baz
console.log(e.message); //bazMessage
console.log(e.stack); //stacktrace
}

--

--

zenibako.lee
zenibako.lee

Written by zenibako.lee

backend engineer, JS, Node, AWS

No responses yet