Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5424a10

Browse files
[프라미스와 에러 핸들링] 번역
1 parentc3d571a commit5424a10

File tree

1 file changed

+68
-68
lines changed

1 file changed

+68
-68
lines changed
Lines changed: 68 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11

2-
#Error handling with promises
2+
#프라미스와 에러 핸들링
33

4-
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핸들러로 넘어갑니다. 이는 실무에서 아주 유용하게 사용됩니다.
55

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`에서 이를 처리할 수 있습니다.
77

88
```js run
99
*!*
10-
fetch('https://no-such-server.blabla')//rejects
10+
fetch('https://no-such-server.blabla')//거부
1111
*/!*
1212
.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 (출력되는 내용은 다를 수 있음)
1414
```
1515

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` 뒤에 올 수 있습니다.
1717

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`를 붙이면 에러 전부를 간단하게 잡을 수 있습니다.
1919

2020
```js run
2121
fetch('/article/promise-chaining/user.json')
@@ -38,167 +38,167 @@ fetch('/article/promise-chaining/user.json')
3838
*/!*
3939
```
4040

41-
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`에서 에러를 잡게 됩니다.
4242

43-
##Implicit try..catch
43+
##암시적 try..catch
4444

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처럼 다룹니다.
4646

47-
For instance, this code:
47+
예시:
4848

4949
```js run
5050
newPromise((resolve,reject)=> {
5151
*!*
52-
thrownewError("Whoops!");
52+
thrownewError("에러 발생!");
5353
*/!*
54-
}).catch(alert);// Error:Whoops!
54+
}).catch(alert);// Error:에러 발생!
5555
```
5656

57-
...Works exactly the same as this:
57+
위 예시는 아래 예시와 똑같이 동작합니다.
5858

5959
```js run
6060
newPromise((resolve,reject)=> {
6161
*!*
62-
reject(newError("Whoops!"));
62+
reject(newError("에러 발생!"));
6363
*/!*
64-
}).catch(alert);// Error:Whoops!
64+
}).catch(alert);// Error:에러 발생!
6565
```
6666

67-
The "invisible`try..catch`" around the executor automatically catches the error and turns it into rejected promise.
67+
executor 주위의 '암시적`try..catch`'는 자동으로 에러를 잡고, 이를 거부상태의 프라미스로 변경시킵니다.
6868

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`를 사용해 에러를 던지면, 이 자체가 거부된 프라미스를 의미하게 됩니다. 따라서 제어 흐름이 가장 가까운 에러 핸들러로 넘어갑니다.
7070

71-
Here's an example:
71+
예시:
7272

7373
```js run
7474
newPromise((resolve,reject)=> {
7575
resolve("ok");
7676
}).then((result)=> {
7777
*!*
78-
thrownewError("Whoops!");//rejects the promise
78+
thrownewError("에러 발생!");//프라미스가 거부됨
7979
*/!*
80-
}).catch(alert);// Error:Whoops!
80+
}).catch(alert);// Error:에러 발생!
8181
```
8282

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`가 프로그래밍 에러를 어떻게 처리하는지 살펴봅시다.
8484

8585
```js run
8686
newPromise((resolve,reject)=> {
8787
resolve("ok");
8888
}).then((result)=> {
8989
*!*
90-
blabla();//no such function
90+
blabla();//존재하지 않는 함수
9191
*/!*
9292
}).catch(alert);// ReferenceError: blabla is not defined
9393
```
9494

95-
The final`.catch` not only catches explicit rejections, but also occasional errors in the handlers above.
95+
마지막`.catch`는 이렇게 명시적인 거부뿐만 아니라 핸들러 위쪽에서 비정상적으로 발생한 에러 또한 잡습니다.
9696

97-
##Rethrowing
97+
##다시 던지기
9898

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` 핸들러에서 발생한 모든 에러를 처리할 수 있습니다.
100100

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`에선 에러를 분석하고, 처리할 수 없는 에러라 판단되면 다시 던질 때가 있습니다. 프라미스에도 유사한 일을 할 수 있습니다.
102102

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` 핸들러로 제어 흐름이 넘어가 실행이 이어집니다.
104104

105-
In the example below the`.catch` successfully handles the error:
105+
아래 예시의`.catch`는 에러를 성공적으로 처리합니다.
106106

107107
```js run
108-
//the execution: catch -> then
108+
//실행 순서: catch -> then
109109
newPromise((resolve,reject)=> {
110110

111-
thrownewError("Whoops!");
111+
thrownewError("에러 발생!");
112112

113113
}).catch(function(error) {
114114

115-
alert("The error is handled, continue normally");
115+
alert("에러가 잘 처리되었습니다. 정상적으로 실행이 이어집니다.");
116116

117-
}).then(()=>alert("Next successful handler runs"));
117+
}).then(()=>alert("다음 핸들러가 실행됩니다."));
118118
```
119119

120-
Here the`.catch`block finishes normally. So the next successful`.then` handler is called.
120+
`.catch`블럭이 정상적으로 종료되었기 때문에 다음 성공 핸들러,`.then`이 호출된 것을 확인할 수 있습니다.
121121

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` 처리 방법만 알고 있음) 에러를 다시 던집니다.
123123

124124
```js run
125-
//the execution: catch -> catch -> then
125+
//실행 순서: catch -> catch -> then
126126
newPromise((resolve,reject)=> {
127127

128-
thrownewError("Whoops!");
128+
thrownewError("에러 발생!");
129129

130130
}).catch(function(error) {// (*)
131131

132132
if (errorinstanceofURIError) {
133-
//handle it
133+
//에러 처리
134134
}else {
135-
alert("Can't handle such error");
135+
alert("처리할 수 없는 에러");
136136

137137
*!*
138-
throw error;//throwing this or another error jumps to the next catch
138+
throw error;//에러 다시 던지기
139139
*/!*
140140
}
141141

142142
}).then(function() {
143-
/*doesn't run here*/
143+
/*여기는 실행되지 않습니다.*/
144144
}).catch(error=> {// (**)
145145

146-
alert(`The unknown error has occurred:${error}`);
147-
//don't return anything=>execution goes the normal way
146+
alert(`알 수 없는 에러가 발생함:${error}`);
147+
//반환값이 없음=>실행이 계속됨
148148

149149
});
150150
```
151151

152-
The execution jumps from the first`.catch``(*)` to the next one`(**)` down the chain.
152+
실행 흐름이 첫 번째`.catch``(*)`로 넘어갔다가 다음`.catch``(**)`로 이어지는 것을 확인할 수 있습니다.
153153

154-
##Unhandled rejections
154+
##처리되지 못한 거부
155155

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`를 추가하지 못하는 경우처럼 말이죠.
157157

158158
```js untrusted run refresh
159159
newPromise(function() {
160-
noSuchFunction();//Error here (no such function)
160+
noSuchFunction();//에러 (존재하지 않는 함수)
161161
})
162162
.then(()=> {
163-
//successful promise handlers, one or more
164-
});//without .catch at the end!
163+
//성공상태의 프라미스를 처리하는 핸들러. 한 개 혹은 여러 개가 있을 수 있음
164+
});//끝에 .catch가 없음!
165165
```
166166

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핸들러로 넘어갑니다. 그런데 위 예시엔 예외를 처리해 줄 핸들러가 없어서 에러가 '갇혀버립니다'. 에러를 처리할 코드가 없기 때문입니다.
168168

169-
In practice, just like with regular unhandled errors in code, it means that something has terribly gone wrong.
169+
이런 식으로 코드에 처리하지 못한 에러가 남게 되면 실무에선 끔찍한 일이 발생합니다.
170170

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`에서 처리하지 못하는 경우를 생각해봅시다. 스크립트가 죽고 콘솔 창에 메시지가 출력되겠죠. 거부된 프라미스를 처리하지 못했을 때도 유사한 일이 발생합니다.
172172

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+
자바스크립트 엔진은 프라미스 거부를 추적하다가 위와 같은 상황이 발생하면 전역 에러를 생성합니다. 콘솔창을 열고 위 예시를 실행하면 전역 에러를 확인할 수 있습니다.
174174

175-
In the browser we can catch such errors using the event`unhandledrejection`:
175+
브라우저 환경에선 이런 에러를`unhandledrejection` 이벤트로 잡을 수 있습니다.
176176

177177
```js run
178178
*!*
179179
window.addEventListener('unhandledrejection',function(event) {
180-
//the event object has two special properties:
181-
alert(event.promise);// [object Promise] -the promise that generated the error
182-
alert(event.reason);// Error:Whoops! -the unhandled error object
180+
//이벤트엔 두 개의 특별 프로퍼티가 있습니다.
181+
alert(event.promise);// [object Promise] -에러를 생성하는 프라미스
182+
alert(event.reason);// Error:에러 발생! -처리하지 못한 에러 객체
183183
});
184184
*/!*
185185

186186
newPromise(function() {
187-
thrownewError("Whoops!");
188-
});//no catch to handle the error
187+
thrownewError("에러 발생!");
188+
});//에러 처리 핸들러, catch가 없음
189189
```
190190

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)에 정의된 표준 이벤트입니다.
192192

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`객체를 받기 때문에 이 핸들러 안에서 원하는 작업을 할 수 있습니다.
194194

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+
대개 이런 에러는 회복할 수 없기 때문에 개발자로서 할 수 있는 최선의 방법은 사용자에게 문제 상황을 알리고 가능하다면 서버에 에러 정보를 보내는 것입니다.
196196

197-
In non-browser environments like Node.js there are other ways to track unhandled errors.
197+
Node.js같은 기타 호스트 환경에도 처리하지 못한 에러를 다루는 방법을 여러 가지 제공합니다.
198198

199-
##Summary
199+
##요약
200200

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`을, 다른 환경에선 유사한 핸들러를 사용). 애플리케이션이 아무런 설명도 없이 '그냥 죽는걸' 방지합시다.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp