Skip to content

Commit 1de023d

Browse files
authored
Merge pull request etroynov#79 from artsurkan/exceptions.md
translate exceptions.md
2 parents 73d0622 + 533ff71 commit 1de023d

File tree

1 file changed

+45
-45
lines changed

1 file changed

+45
-45
lines changed

docs/types/exceptions.md

Lines changed: 45 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,170 +1,170 @@
1-
# Exception Handling
1+
# Обработка исключений
22

3-
JavaScript has an `Error` class that you can use for exceptions. You throw an error with the `throw` keyword. You can catch it with a `try` / `catch` block pair e.g.
3+
В JavaScript есть класс `Error`, который можно использовать для исключений. Вы выбрасываете ошибку с ключевым словом `throw`. Вы можете отловить её с помощью блоков `try` / `catch`, например:
44

55
```js
66
try {
7-
throw new Error('Something bad happened');
7+
throw new Error('Случилось что-то плохое');
88
}
99
catch(e) {
1010
console.log(e);
1111
}
1212
```
1313

14-
## Error Sub Types
14+
## Подтипы ошибок
1515

16-
Beyond the built in `Error` class there are a few additional built-in error classes that inherit from `Error` that the JavaScript runtime can throw:
16+
Помимо встроенного класса `Error`, существует несколько дополнительных встроенных классов ошибок, которые наследуются от `Error`, которые может генерировать среда выполнения JavaScript:
1717

1818
### RangeError
1919

20-
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
20+
Создается экземпляр ошибки, которая возникает, когда числовая переменная или параметр выходит за пределы допустимого диапазона.
2121

2222
```js
23-
// Call console with too many arguments
24-
console.log.apply(console, new Array(1000000000)); // RangeError: Invalid array length
23+
// Вызов консоли с слишком большим количеством параметров
24+
console.log.apply(console, new Array(1000000000)); // RangeError: Невалидная длина массива
2525
```
2626

2727
### ReferenceError
2828

29-
Creates an instance representing an error that occurs when de-referencing an invalid reference. e.g.
29+
Создается экземпляр ошибки, которая возникает при разыменовании недействительной ссылки. Например:
3030

3131
```js
3232
'use strict';
33-
console.log(notValidVar); // ReferenceError: notValidVar is not defined
33+
console.log(notValidVar); // ReferenceError: notValidVar не определена
3434
```
3535

3636
### SyntaxError
3737

38-
Creates an instance representing a syntax error that occurs while parsing code that isn't valid JavaScript.
38+
Создается экземпляр ошибки, возникающей при синтаксическом анализе кода, который не является допустимым в JavaScript.
3939

4040
```js
41-
1***3; // SyntaxError: Unexpected token *
41+
1***3; // SyntaxError: Непредвиденный токен *
4242
```
4343

4444
### TypeError
4545

46-
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
46+
Создается экземпляр ошибки, которая возникает, когда переменная или параметр имеет недопустимый тип.
4747

4848
```js
49-
('1.2').toPrecision(1); // TypeError: '1.2'.toPrecision is not a function
49+
('1.2').toPrecision(1); // TypeError: '1.2'.toPrecision не является функцией
5050
```
5151

5252
### URIError
5353

54-
Creates an instance representing an error that occurs when `encodeURI()` or `decodeURI()` are passed invalid parameters.
54+
Создается экземпляр ошибки, которая возникает, когда в `encodeURI()` или `decodeURI()` передаются недопустимые параметры.
5555

5656
```js
57-
decodeURI('%'); // URIError: URI malformed
57+
decodeURI('%'); // URIError: URI неправильно сформирован
5858
```
5959

60-
## Always use `Error`
60+
## Всегда используйте `Error`
6161

62-
Beginner JavaScript developers sometimes just throw raw strings e.g.
62+
Начинающие разработчики JavaScript иногда просто бросают необработанные строки, например.
6363

6464
```js
6565
try {
66-
throw 'Something bad happened';
66+
throw 'Случилось что-то плохое';
6767
}
6868
catch(e) {
6969
console.log(e);
7070
}
7171
```
7272

73-
*Don't do that*. The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated with the `stack` property.
73+
*Не делайте так*. Основное преимущество объектов `Error` состоит в том, что автоматически отслеживается где они были созданы и произошли с помощью свойства `stack`.
7474

75-
Raw strings result in a very painful debugging experience and complicate error analysis from logs.
75+
Необработанные строки приводят к очень болезненной отладке и затрудняют анализ ошибок из логов.
7676

77-
## You don't have to `throw` an error
77+
## Вам не нужно `выбрасывать` ошибку
7878

79-
It is okay to pass an `Error` object around. This is conventional in Node.js callback style code which takes callbacks with the first argument as an error object.
79+
Это нормально передавать объект `Error`. Это общепринятый код в Node.js колбэк стиле, который принимает колбэк первым параметром как объект ошибки.
8080

8181
```js
8282
function myFunction (callback: (e?: Error)) {
8383
doSomethingAsync(function () {
8484
if (somethingWrong) {
85-
callback(new Error('This is my error'))
85+
callback(new Error('Это моя ошибка'))
8686
} else {
8787
callback();
8888
}
8989
});
9090
}
9191
```
9292

93-
## Exceptional cases
93+
## Исключительные случаи
9494

95-
`Exceptions should be exceptional` is a common saying in computer science. There are a few reasons why this is true for JavaScript (and TypeScript) as well.
95+
`Исключения должны быть исключительными` - это частая поговорка в компьютерных науках. Это одинаково справедливо и для JavaScript (и для TypeScript) по нескольким причинам.
9696

97-
### Unclear where it is thrown
97+
### Неясно откуда брошено исключение
9898

99-
Consider the following piece of code:
99+
Рассмотрим следующий фрагмент кода:
100100

101101
```js
102102
try {
103103
const foo = runTask1();
104104
const bar = runTask2();
105105
}
106106
catch(e) {
107-
console.log('Error:', e);
107+
console.log('Ошибка:', e);
108108
}
109109
```
110110

111-
The next developer cannot know which function might throw the error. The person reviewing the code cannot know without reading the code for task1 / task2 and other functions they might call etc.
111+
Следующий разработчик не знает, какая функция может вызвать ошибку. Человек, просматривающий код, не может знать об этом, не прочитав код для task1 / task2 и других функций, которые они могут вызвать внутри себя и т.д.
112112

113-
### Makes graceful handling hard
113+
### Делает поэтапную обработку сложной
114114

115-
You can try to make it graceful with explicit catch around each thing that might throw:
115+
Вы можете попытаться сделать обработку поэтапной с помощью явного отлова вокруг каждого места, которое может бросить ошибку:
116116

117117
```js
118118
try {
119119
const foo = runTask1();
120120
}
121121
catch(e) {
122-
console.log('Error:', e);
122+
console.log('Ошибка:', e);
123123
}
124124
try {
125125
const bar = runTask2();
126126
}
127127
catch(e) {
128-
console.log('Error:', e);
128+
console.log('Ошибка:', e);
129129
}
130130
```
131131

132-
But now if you need to pass stuff from the first task to the second one the code becomes messy: (notice `foo` mutation requiring `let` + explicit need for annotating it because it cannot be inferred from the return of `runTask1`):
132+
Но теперь, если вам нужно передать что-то из первой задачи во вторую, код становится грязным: (обратите внимание на мутацию `foo`, требующую `let` + явную необходимость описывать ее, потому что это не может быть логически выведено от возврата `runTask1`):
133133

134134
```ts
135-
let foo: number; // Notice use of `let` and explicit type annotation
135+
let foo: number; // Обратите внимание на использование `let` и явное описание типа
136136
try {
137137
foo = runTask1();
138138
}
139139
catch(e) {
140-
console.log('Error:', e);
140+
console.log('Ошибка:', e);
141141
}
142142
try {
143143
const bar = runTask2(foo);
144144
}
145145
catch(e) {
146-
console.log('Error:', e);
146+
console.log('Ошибка:', e);
147147
}
148148
```
149149

150-
### Not well represented in the type system
150+
### Не очень хорошо отражено в системе типов
151151

152-
Consider the function:
152+
Рассмотрим функцию:
153153

154154
```ts
155155
function validate(value: number) {
156-
if (value < 0 || value > 100) throw new Error('Invalid value');
156+
if (value < 0 || value > 100) throw new Error('Невалидное значение');
157157
}
158158
```
159159

160-
Using `Error` for such cases is a bad idea as it is not represented in the type definition for the validate function (which is `(value:number) => void`). Instead a better way to create a validate method would be:
160+
Использование `Error` для таких случаев - плохая идея, так как ошибка не отражена в определении типа для проверки функции `(value:number) => void`. Вместо этого лучший способ создать метод проверки:
161161

162162
```ts
163163
function validate(value: number): {error?: string} {
164-
if (value < 0 || value > 100) return {error:'Invalid value'};
164+
if (value < 0 || value > 100) return {error:'Невалидное значение'};
165165
}
166166
```
167167

168-
And now its represented in the type system.
168+
И теперь это отражено в системе типов.
169169

170-
> Unless you want to handle the error in a very generic (simple / catch-all etc) way, don't *throw* an error.
170+
> Если вы не хотите обрабатывать ошибку очень общим (простым / универсальным и т.д.) способом, не *бросайте* ошибку.

0 commit comments

Comments
 (0)