현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.
에러 객체를 생성한다.
문법
new Error([message[, fileName[,lineNumber]]])
파라미터
message
- 에러에 대한 설명
fileName
- 생성된
Error
객체에 대한fileName
속성값. 기본값은 Error() 생성자를 호출한 코드를 포함하고 있는 파일명. lineNumber
- 생성된
Error
객체에 대한lineNumber
속성값. 기본값은 Error() 생성자 호출을 포함하고 있는 줄번호.
설명
런타임 에러가 발생하면 새로운 Error 객체를 생성하고 던진다.
이 페이지는 Error
객체의 사용법과 생성함수로서의 사용법을 문서화한다. Error
인스턴스에 의해 상속받은 속성과 메소드 리스트에 대해서는 Error.prototype
를 참고하세요.
에러 타입
일반적인 Error 생성자외에도 자바스크립트에는 6개의 코어 에러 생성자가 있다. 클라이언트측 예외에 대해서는 Exception Handling Statements를 참고하세요.
EvalError
- 전역함수 eval()에 의하여 발생하는 에러 인스턴스를 생성한다.
InternalError
- 자바스크립트 엔진 안에서 내부 에러가 발생했을 때 이에 해당하는 에러 인스턴스를 생성한다. (예 : 너무 많은 재귀호출)
RangeError
- 숫자 변수나 파라미터가 유효한 범위를 벗어났을 때 발생하는 에러 인스턴스를 생성한다.
ReferenceError
- 잘못된 참조를 했을 때 발생하는 에러 인스턴스를 생성한다.
SyntaxError
eval()
함수로 코드를 해석하는 중에 발생하는 문법 에러 인스턴스를 생성한다.TypeError
- 변수나 파라미터가 적절한 타입이 아닐때 발생하는 에러 인스턴스를 생성한다.
URIError
encodeURI()
나decodeURl()
함수에 부적절한 파라미터가 넘겨졌을 때 발생하는 에러 인스턴스를 생성한다.
Properties
Error.prototype
Error
인스턴스에 대한 속성 추가를 허용한다.
Methods
전역 Error
객체는 자신의 메소드는 가지지 않는다. 하지만, 프로토타입 체인을 통하여 메소드를 상속받고 있다.
Error
instances
All Error
instances and instances of non-generic errors inherit from Error.prototype
. As with all constructor functions, you can use the prototype of the constructor to add properties or methods to all instances created with that constructor.
Properties
Standard properties
Error.prototype.constructor
- Specifies the function that created an instance's prototype.
Error.prototype.message
- Error message.
Error.prototype.name
- Error name.
Vendor-specific extensions
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Microsoft
Error.prototype.description
- Error description. Similar to
message
. Error.prototype.number
- Error number.
Mozilla
Error.prototype.fileName
- Path to file that raised this error.
Error.prototype.lineNumber
- Line number in file that raised this error.
Error.prototype.columnNumber
- Column number in line that raised this error.
Error.prototype.stack
- Stack trace.
Methods
Error.prototype.toSource()
- Returns a string containing the source of the specified
Error
object; you can use this value to create a new object. Overrides theObject.prototype.toSource()
method. Error.prototype.toString()
- Returns a string representing the specified object. Overrides the
Object.prototype.toString()
method.
예제들
예제: 일반적인 에러 던지기
보통 throw
키워드를 이용하여 Error 객체를 던지면서 생성한다. try...catch
구문을 이용하여 에러를 처리할 수 있다:
try { throw new Error("Whoops!"); } catch (e) { alert(e.name + ": " + e.message); }
예제: 특정한 에러 처리하기
this should probably be removed에러의 constructor
속성으로 특정 에러 타입에 대해서만 처리를 할 수 있다. 또는, 최신의 자바스크립트 엔진에 대해 코드를 작성한다면,instanceof
키워드를 이용할 수 있다.:
try { foo.bar(); } catch (e) { if (e instanceof EvalError) { alert(e.name + ": " + e.message); } else if (e instanceof RangeError) { alert(e.name + ": " + e.message); } // ... etc }
사용자정의 에러 타입
Error
에서 파생된 자신만의 에러 타입을 정의하여 throw new MyError()
에러를 발생시키고 instanceof MyError
로 예외 처리 단계에서 에러 타입 체크를 원할 것이다. 이렇게 하는 일반적인 방법은 아래에 설명된다.
적어도 Firefox에서 생성된 MyError
인스턴스는 부정확한 lineNumber
와 fileName
을 보고한다는 것을 숙지하세요.
또한 Stackoverflow에 논의된 "What's a good way to extend Error in JavaScript?"도 읽어보세요.
// Create a new object, that prototypally inherits from the Error constructor. function MyError(message) { this.name = "MyError"; this.message = message || "Default Message"; } MyError.prototype = new Error(); MyError.prototype.constructor = MyError; try { throw new MyError(); } catch (e) { console.log(e.name); // "MyError" console.log(e.message); // "Default Message" } try { throw new MyError("custom message"); } catch (e) { console.log(e.name); // "MyError" console.log(e.message); // "custom message" }