aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/reference/global_objects/error/index.html
blob: 986cb5afa0b8fa01550a2abd98e5715bfe147781 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
---
title: Error
slug: Web/JavaScript/Reference/Global_Objects/Error
tags:
  - Error
  - JavaScript
  - Reference
translation_of: Web/JavaScript/Reference/Global_Objects/Error
---
<div>{{JSRef}}</div>

<p><span class="seoSummary"><strong><code>Error</code></strong> 생성자는 오류 객체를 생성합니다.</span> <code>Error</code> 객체의 인스턴스는 런타임 오류가 발생했을 때 던져집니다. <code>Error</code> 객체를 사용자 지정 예외의 기반 객체로 사용할 수도 있습니다.</p>

<h2 id="Syntax" name="Syntax">구문</h2>

<pre class="syntaxbox">new Error([<em>message</em>[, <em>fileName</em>[, <em>lineNumber</em>]]])</pre>

<h3 id="Parameters" name="Parameters">매개변수</h3>

<dl>
 <dt><code>message</code> {{optional_inline}}</dt>
 <dd>사람이 읽을 수 있는, 오류에 대한 설명.</dd>
 <dt><code>fileName</code> {{optional_inline}} {{non-standard_inline}}</dt>
 <dd>생성할 <code>Error</code> 객체의 <code>fileName</code> 속성 값. 기본값은 <code>Error</code> 생성자를 호출한 코드를 포함하고 있는 파일의 이름입니다.</dd>
 <dt><code>lineNumber</code> {{optional_inline}} {{non-standard_inline}}</dt>
 <dd>생성할 <code>Error</code> 객체의 <code>lineNumber</code> 속성 값. 기본값은 <code>Error</code> 생성자 호출을 포함한 줄 번호입니다.</dd>
</dl>

<h2 id="Description" name="Description">설명</h2>

<p>런타임 오류는 새로운 <code>Error</code> 객체를 생성하고 던집니다.</p>

<p>이 페이지는 <code>Error</code> 오브젝트 자체와, 생성자 함수로서의 사용처를 다룹니다. <code>Error</code> 인스턴스가 상속하는 속성과 메서드는 {{jsxref("Error.prototype")}}을 참고하세요.</p>

<h3 id="함수로_사용">함수로 사용</h3>

<p><code>Error</code>{{jsxref("Operators/new", "new")}} 없이 함수로 사용하면 <code>Error</code> 객체를 반환합니다. 즉 <code>Error</code>를 직접 호출해도 인스턴스를 만드는 것과 동일한 결과를 얻을 수 있습니다.</p>

<pre class="brush: js">// 이렇게 호출하는 것과
const x = Error('I was created using a function call!');
​​​​// 이렇게 사용하는게 동일
const y = new Error('I was constructed via the "new" keyword!');
</pre>

<h3 id="Error_types" name="Error_types">오류 유형</h3>

<p>JavaScript에는 일반적인 <code>Error</code> 생성자 외에도 7개의 중요 오류 생성자가 존재합니다. 클라이언트측 예외에 대해서는 <a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#예외처리문">제어 흐름과 에러 처리</a>를 참고하세요.</p>

<dl>
 <dt>{{jsxref("EvalError")}}</dt>
 <dd>전역 함수 {{jsxref("eval", "eval()")}}에서 발생하는 오류의 인스턴스를 생성합니다.</dd>
 <dt>{{jsxref("InternalError")}} {{non-standard_inline}}</dt>
 <dd>JavaScript 엔진의 내부에서 오류가 발생했음을 나타내는 오류 인스턴스를 생성합니다.</dd>
 <dt>{{jsxref("RangeError")}}</dt>
 <dd>숫자 변수나 매개변수가 유효한 범위를 벗어났음을 나타내는 오류 인스턴스를 생성합니다.</dd>
 <dt>{{jsxref("ReferenceError")}}</dt>
 <dd>잘못된 참조를 했음을 나타내는 오류 인스턴스를 생성합니다.</dd>
 <dt>{{jsxref("SyntaxError")}}</dt>
 <dd>{{jsxref("eval", "eval()")}}이 코드를 분석하는 중 잘못된 구문을 만났음을 나타내는 오류 인스턴스를 생성합니다.</dd>
 <dt>{{jsxref("TypeError")}}</dt>
 <dd>변수나 매개변수가 유효한 자료형이 아님을 나타내는 오류 인스턴스를 생성합니다.</dd>
 <dt>{{jsxref("URIError")}}</dt>
 <dd>{{jsxref("encodeURI", "encodeURI()")}}나 {{jsxref("decodeURI", "decodeURl()")}} 함수에 부적절한 매개변수를 제공했을 때 발생하는 오류의 인스턴스를 생성합니다.</dd>
</dl>

<h2 id="Properties" name="Properties">속성</h2>

<dl>
 <dt>{{jsxref("Error.prototype")}}</dt>
 <dd><code>Error</code> 인스턴스에 속성을 추가할 수 있습니다.</dd>
</dl>

<h2 id="Methods" name="Methods">메서드</h2>

<p>전역 <code>Error</code> 객체는 자신의 메서드를 가지지 않습니다. 그러나 프로토타입 체인을 통해 일부 메서드를 상속받습니다.</p>

<h2 id="Error_instances" name="Error_instances"><code>Error</code> 인스턴스</h2>

<div>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '설명')}}</div>

<h3 id="속성">속성</h3>

<div>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '속성')}}</div>

<h3 id="메서드">메서드</h3>

<div>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '메서드')}}</div>

<h2 id="Examples" name="Examples">예제</h2>

<h3 id="Example:_Throwing_a_generic_error" name="Example:_Throwing_a_generic_error">일반적인 오류 던지기</h3>

<p><code>Error</code> 객체를 생성한 후엔 대개 {{jsxref("Statements/throw", "throw")}} 키워드를 이용해 던집니다. {{jsxref("Statements/try...catch", "try...catch")}} 구문을 이용하여 오류를 처리할 수 있습니다.</p>

<pre class="brush: js">try {
  throw new Error("이런!");
} catch (e) {
  alert(e.name + ": " + e.message);
}
</pre>

<h3 id="Example:_Handling_a_specific_error" name="Example:_Handling_a_specific_error">특정 오류 처리하기</h3>

<p><span class="comment">this should probably be removed</span>오류의 {{jsxref("Object.prototype.constructor", "constructor")}} 속성을 판별해 특정 오류에 대해서만 처리를 할 수 있습니다. 현대적인 JavaScript 엔진의 코드를 작성한다면 {{jsxref("Operators/instanceof", "instanceof")}} 키워드를 이용할 수도 있습니다.</p>

<pre class="brush: js">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
}
</pre>

<h3 id="사용자_정의_에러_타입">사용자 정의 에러 타입</h3>

<p><code>throw new MyError()</code> 이후 <code>instanceof MyError</code>로 직접 만든 오류를 판별할 수 있도록 <code>Error</code>의 파생 오류 정의를 고려해보세요. 더 깔끔하고 일관적인 오류 처리 코드를 작성할 수 있습니다. StackOverflow의 <a href="http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript">"What's a good way to extend Error in JavaScript?"</a>를 방문해 심도 있는 논의를 읽어보세요.</p>

<h4 id="ES6_사용자_정의_오류_클래스">ES6 사용자 정의 오류 클래스</h4>

<div class="warning">
<p>Babel 버전 7 미만으로 사용자 정의 오류 클래스를 처리하려면 {{jsxref("Object.defineProperty()")}} 메서드를 사용해 정의해야만 합니다. 그렇지 않으면 오래된 Babel 및 다른 트랜스파일러가 <a href="https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend">추가 설정</a> 없이 코드를 처리할 수 없습니다.</p>
</div>

<div class="note">
<p>ES2015 클래스를 사용할 때, 일부 브라우저는 <code>CustomError</code> 생성자를 스택 트레이스에 포함합니다.</p>
</div>

<pre class="brush: js">class CustomError extends Error {
  constructor(foo = 'bar', ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // 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.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
}</pre>

<h4 id="ES5_사용자_정의_오류_객체">ES5 사용자 정의 오류 객체</h4>

<div class="warning">
<p>프로토타입 선언을 사용하면 모든 브라우저가 <code>CustomError</code> 생성자를 스택 트레이스에 포함합니다.</p>
</div>

<pre class="brush: js">function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

CustomError.prototype = Object.create(Error.prototype, {
  constructor: {
    value: Error,
    enumerable: false,
    writable: true,
    configurable: true
  }
});

if (Object.setPrototypeOf){
  Object.setPrototypeOf(CustomError, Error);
} else {
  CustomError.__proto__ = Error;
}


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

<h2 id="See_also" name="See_also">명세</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES1')}}</td>
   <td>{{Spec2('ES1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.1.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.11', 'Error')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-error-objects', 'Error')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="브라우저_호환성">브라우저 호환성</h2>



<p>{{Compat("javascript.builtins.Error")}}</p>

<h2 id="See_also" name="See_also">같이 보기</h2>

<ul>
 <li>{{jsxref("Error.prototype")}}</li>
 <li>{{jsxref("Statements/throw", "throw")}}</li>
 <li>{{jsxref("Statements/try...catch", "try...catch")}}</li>
</ul>