You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Promise chains are great at error handling. When a promise rejects, the control jumps to the closestrejectionhandler. That's very convenient in practice.
4
+
프라미스 체인은 에러를 잘 처리합니다. 프라미스가 거부되면 제어 흐름이 제일 가까운rejection핸들러로 넘어갑니다. 이는 실무에서 아주 유용하게 사용됩니다.
5
5
6
-
For instance, in the code below the URL to`fetch` is wrong (no such site) and`.catch` handles the error:
6
+
`fetch`에 넘겨주는 URL(없는 주소)이 잘못된 경우를 살펴봅시다. 에러가 발생하지만`.catch`에서 이를 처리할 수 있습니다.
7
7
8
8
```js run
9
9
*!*
10
-
fetch('https://no-such-server.blabla')//rejects
10
+
fetch('https://no-such-server.blabla')//거부
11
11
*/!*
12
12
.then(response=>response.json())
13
-
.catch(err=>alert(err))// TypeError: failed to fetch (the text may vary)
13
+
.catch(err=>alert(err))// TypeError: failed to fetch (출력되는 내용은 다를 수 있음)
14
14
```
15
15
16
-
As you can see, the`.catch` doesn't have to be immediate. It may appear after one or maybe several`.then`.
16
+
위 예시를 통해 알 수 있듯이`.catch`는 바로 나올 필요가 없습니다. 하나 혹은 여러 개의`.then` 뒤에 올 수 있습니다.
17
17
18
-
Or, maybe, everything is all right with the site, but the response is not valid JSON. The easiest way to catch all errors is to append`.catch` to the end of chain:
18
+
이번엔 사이트에는 아무런 문제가 없지만, 응답으로 받은 JSON의 형식이 잘못된 경우를 살펴보겠습니다. 체인 끝에`.catch`를 붙이면 에러 전부를 간단하게 잡을 수 있습니다.
Normally, such`.catch` doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it.
41
+
정상적인 경우라면, 예시를 실행했을 때`.catch`는 절대 트리거 되지 않습니다. 그런데 네트워크 문제, 잘못된 형식의 JSON 등으로 인해 프라미스 중 하나라도 거부되면`.catch`에서 에러를 잡게 됩니다.
42
42
43
-
##Implicit try..catch
43
+
##암시적 try..catch
44
44
45
-
The code of a promise executor and promise handlers has an "invisible`try..catch`" around it. If an exception happens, it gets caught and treated as a rejection.
45
+
프라미스 executor와 프라미스 핸들러 코드 주위엔 '보이지 않는`try..catch`'가 있습니다. 예외가 발생하면 암시적`try..catch`에서 예외를 잡고, 이를 reject처럼 다룹니다.
46
46
47
-
For instance, this code:
47
+
예시:
48
48
49
49
```js run
50
50
newPromise((resolve,reject)=> {
51
51
*!*
52
-
thrownewError("Whoops!");
52
+
thrownewError("에러 발생!");
53
53
*/!*
54
-
}).catch(alert);// Error:Whoops!
54
+
}).catch(alert);// Error:에러 발생!
55
55
```
56
56
57
-
...Works exactly the same as this:
57
+
위 예시는 아래 예시와 똑같이 동작합니다.
58
58
59
59
```js run
60
60
newPromise((resolve,reject)=> {
61
61
*!*
62
-
reject(newError("Whoops!"));
62
+
reject(newError("에러 발생!"));
63
63
*/!*
64
-
}).catch(alert);// Error:Whoops!
64
+
}).catch(alert);// Error:에러 발생!
65
65
```
66
66
67
-
The "invisible`try..catch`" around the executor automatically catches the error and turns it into rejected promise.
67
+
executor 주위의 '암시적`try..catch`'는 자동으로 에러를 잡고, 이를 거부상태의 프라미스로 변경시킵니다.
68
68
69
-
This happens not only in theexecutorfunction, but in its handlers as well. If we`throw` inside a`.then` handler, that means a rejected promise, so the control jumps to the nearest error handler.
69
+
이런 일은executor함수뿐만 아니라 핸들러에서도 발생합니다.`.then` 핸들러 안에서`throw`를 사용해 에러를 던지면, 이 자체가 거부된 프라미스를 의미하게 됩니다. 따라서 제어 흐름이 가장 가까운 에러 핸들러로 넘어갑니다.
70
70
71
-
Here's an example:
71
+
예시:
72
72
73
73
```js run
74
74
newPromise((resolve,reject)=> {
75
75
resolve("ok");
76
76
}).then((result)=> {
77
77
*!*
78
-
thrownewError("Whoops!");//rejects the promise
78
+
thrownewError("에러 발생!");//프라미스가 거부됨
79
79
*/!*
80
-
}).catch(alert);// Error:Whoops!
80
+
}).catch(alert);// Error:에러 발생!
81
81
```
82
82
83
-
This happens for all errors, not just those caused by the`throw` statement. For example, a programming error:
83
+
`throw`문이 만든 에러뿐만 아니라 모든 종류의 에러가 암시적`try..catch`에서 처리됩니다. 암시적`try..catch`가 프로그래밍 에러를 어떻게 처리하는지 살펴봅시다.
84
84
85
85
```js run
86
86
newPromise((resolve,reject)=> {
87
87
resolve("ok");
88
88
}).then((result)=> {
89
89
*!*
90
-
blabla();//no such function
90
+
blabla();//존재하지 않는 함수
91
91
*/!*
92
92
}).catch(alert);// ReferenceError: blabla is not defined
93
93
```
94
94
95
-
The final`.catch` not only catches explicit rejections, but also occasional errors in the handlers above.
95
+
마지막`.catch`는 이렇게 명시적인 거부뿐만 아니라 핸들러 위쪽에서 비정상적으로 발생한 에러 또한 잡습니다.
96
96
97
-
##Rethrowing
97
+
##다시 던지기
98
98
99
-
As we already noticed,`.catch` at the end of the chain is similar to`try..catch`. We may have as many`.then`handlers as we want, and then use a single`.catch`at the end to handle errors in all of them.
99
+
체인 마지막의`.catch`는`try..catch`와 유사한 역할을 합니다.`.then`핸들러를 원하는 만큼 사용하다 마지막에`.catch`하나만 붙이면,`.then` 핸들러에서 발생한 모든 에러를 처리할 수 있습니다.
100
100
101
-
In a regular`try..catch` we can analyze the error and maybe rethrow it if can't handle. The same thing is possible for promises.
101
+
일반`try..catch`에선 에러를 분석하고, 처리할 수 없는 에러라 판단되면 다시 던질 때가 있습니다. 프라미스에도 유사한 일을 할 수 있습니다.
102
102
103
-
If we`throw` inside`.catch`, then the control goes to the next closest error handler. And if we handle the error and finish normally,then it continues to the closest successful`.then` handler.
103
+
`.catch` 안에서`throw`를 사용하면 제어 흐름이 가장 가까운 곳에 있는 에러 핸들러로 넘어갑니다. 여기서 에러가 성공적으로 처리되면 가장 가까운 곳에 있는`.then` 핸들러로 제어 흐름이 넘어가 실행이 이어집니다.
104
104
105
-
In the example below the`.catch` successfully handles the error:
Here the`.catch`block finishes normally. So the next successful`.then` handler is called.
120
+
`.catch`블럭이 정상적으로 종료되었기 때문에 다음 성공 핸들러,`.then`이 호출된 것을 확인할 수 있습니다.
121
121
122
-
In the example below we see the other situation with`.catch`. The handler`(*)` catches the error and just can't handle it (e.g. it only knows how to handle`URIError`), so it throws it again:
122
+
`.catch`를 활용한 또 다른 사례를 살펴봅시다.`(*)`로 표시한 핸들러에서 에러를 잡는데, 여기서는 에러를 처리하지 못하기 때문에(`URIError` 처리 방법만 알고 있음) 에러를 다시 던집니다.
123
123
124
124
```js run
125
-
//the execution: catch -> catch -> then
125
+
//실행 순서: catch -> catch -> then
126
126
newPromise((resolve,reject)=> {
127
127
128
-
thrownewError("Whoops!");
128
+
thrownewError("에러 발생!");
129
129
130
130
}).catch(function(error) {// (*)
131
131
132
132
if (errorinstanceofURIError) {
133
-
//handle it
133
+
//에러 처리
134
134
}else {
135
-
alert("Can't handle such error");
135
+
alert("처리할 수 없는 에러");
136
136
137
137
*!*
138
-
throw error;//throwing this or another error jumps to the next catch
138
+
throw error;//에러 다시 던지기
139
139
*/!*
140
140
}
141
141
142
142
}).then(function() {
143
-
/*doesn't run here*/
143
+
/*여기는 실행되지 않습니다.*/
144
144
}).catch(error=> {// (**)
145
145
146
-
alert(`The unknown error has occurred:${error}`);
147
-
//don't return anything=>execution goes the normal way
146
+
alert(`알 수 없는 에러가 발생함:${error}`);
147
+
//반환값이 없음=>실행이 계속됨
148
148
149
149
});
150
150
```
151
151
152
-
The execution jumps from the first`.catch``(*)` to the next one`(**)` down the chain.
152
+
실행 흐름이 첫 번째`.catch``(*)`로 넘어갔다가 다음`.catch``(**)`로 이어지는 것을 확인할 수 있습니다.
153
153
154
-
##Unhandled rejections
154
+
##처리되지 못한 거부
155
155
156
-
What happens when an error is not handled? For instance, we forgot to append`.catch` to the end of the chain, like here:
156
+
에러를 처리하지 못하면 무슨 일이 생길까요? 아래 예시처럼 체인 끝에`.catch`를 추가하지 못하는 경우처럼 말이죠.
157
157
158
158
```js untrusted run refresh
159
159
newPromise(function() {
160
-
noSuchFunction();//Error here (no such function)
160
+
noSuchFunction();//에러 (존재하지 않는 함수)
161
161
})
162
162
.then(()=> {
163
-
//successful promise handlers, one or more
164
-
});//without .catch at the end!
163
+
//성공상태의 프라미스를 처리하는 핸들러. 한 개 혹은 여러 개가 있을 수 있음
164
+
});//끝에 .catch가 없음!
165
165
```
166
166
167
-
In case of an error, the promise becomes rejected, and the execution should jump to the closestrejectionhandler. But there is none. So the error gets "stuck". There's no code to handle it.
167
+
에러가 발생하면 프라미스는 거부상태가 되고, 실행 흐름은 가장 가까운rejection핸들러로 넘어갑니다. 그런데 위 예시엔 예외를 처리해 줄 핸들러가 없어서 에러가 '갇혀버립니다'. 에러를 처리할 코드가 없기 때문입니다.
168
168
169
-
In practice, just like with regular unhandled errors in code, it means that something has terribly gone wrong.
169
+
이런 식으로 코드에 처리하지 못한 에러가 남게 되면 실무에선 끔찍한 일이 발생합니다.
170
170
171
-
What happens when a regular error occurs and is not caught by`try..catch`? The script dies with a message in console. Similar thing happens with unhandled promise rejections.
171
+
일반적인 에러가 발생하고 이를`try..catch`에서 처리하지 못하는 경우를 생각해봅시다. 스크립트가 죽고 콘솔 창에 메시지가 출력되겠죠. 거부된 프라미스를 처리하지 못했을 때도 유사한 일이 발생합니다.
172
172
173
-
JavaScript engine tracks such rejections and generates a global error in that case. You can see it in the console if you run the example above.
173
+
자바스크립트 엔진은 프라미스 거부를 추적하다가 위와 같은 상황이 발생하면 전역 에러를 생성합니다. 콘솔창을 열고 위 예시를 실행하면 전역 에러를 확인할 수 있습니다.
174
174
175
-
In the browser we can catch such errors using the event`unhandledrejection`:
175
+
브라우저 환경에선 이런 에러를`unhandledrejection` 이벤트로 잡을 수 있습니다.
alert(event.reason);// Error:에러 발생! -처리하지 못한 에러 객체
183
183
});
184
184
*/!*
185
185
186
186
newPromise(function() {
187
-
thrownewError("Whoops!");
188
-
});//no catch to handle the error
187
+
thrownewError("에러 발생!");
188
+
});//에러 처리 핸들러, catch가 없음
189
189
```
190
190
191
-
The event is the part of the[HTMLstandard](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections).
191
+
`unhandledrejection` 이벤트는[HTML명세서](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections)에 정의된 표준 이벤트입니다.
192
192
193
-
If an error occurs, and there's no`.catch`, the`unhandledrejection`handler triggers, and gets the`event`object with the information about the error, so we can do something.
193
+
브라우저 환경에선 에러가 발생했는데`.catch`가 없으면`unhandledrejection`핸들러가 트리거 됩니다.`unhandledrejection` 핸들러는 에러 정보가 담긴`event`객체를 받기 때문에 이 핸들러 안에서 원하는 작업을 할 수 있습니다.
194
194
195
-
Usually such errors are unrecoverable, so our best way out is to inform the user about the problem and probably report the incident to the server.
195
+
대개 이런 에러는 회복할 수 없기 때문에 개발자로서 할 수 있는 최선의 방법은 사용자에게 문제 상황을 알리고 가능하다면 서버에 에러 정보를 보내는 것입니다.
196
196
197
-
In non-browser environments like Node.js there are other ways to track unhandled errors.
197
+
Node.js같은 기타 호스트 환경에도 처리하지 못한 에러를 다루는 방법을 여러 가지 제공합니다.
198
198
199
-
##Summary
199
+
##요약
200
200
201
-
-`.catch`handles errors in promises of all kinds: be it a`reject()` call, or an error thrown in a handler.
202
-
-We should place`.catch` exactly in places where we want to handle errors and know how to handle them. The handler should analyze errors (custom error classes help) and rethrow unknown ones (maybe they are programming mistakes).
203
-
-It's ok not to use`.catch` at all, if there's no way to recover from an error.
204
-
-In any case we should have the`unhandledrejection`event handler (for browsers, and analogs for other environments), to track unhandled errors and inform the user (and probably our server) about the them, so that our app never "just dies".
201
+
-`.catch`는 프라미스에서 발생한 모든 에러를 다룹니다.`reject()`가 호출되거나 에러가 던져지면`.catch`에서 이를 처리합니다.
202
+
-`.catch`는 에러를 처리하고 싶은 지점에 정확히 위치시켜야 합니다. 물론 어떻게 에러를 처리할지 알고 있어야 하죠. 핸들러 에선 에러를 분석하고(커스텀 에러 클래스가 이때 도움이 됩니다) 알 수 없는 에러(프로그래밍 실수로 발생한 에러일 확률이 높습니다)는 다시 던질 수 있습니다.
203
+
-에러 발생 시, 회복할 방법이 없다면`.catch`를 사용하지 않아도 괜찮습니다.
204
+
-`unhandledrejection`이벤트 핸들러를 사용해 처리되지 않은 에러를 추적하고, 이를 사용자(혹은 서버에)에게 알려서(브라우저 환경에선`unhandledrejection`을, 다른 환경에선 유사한 핸들러를 사용). 애플리케이션이 아무런 설명도 없이 '그냥 죽는걸' 방지합시다.