-
Notifications
You must be signed in to change notification settings - Fork 612
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Добавляет статью "Как дебажить?" #2002
Conversation
js/debugging/index.md
Outdated
|
||
В этой вкладке отображается весь загруженный JS код для страницы. Если у сайта включены source maps, то будут доступны исходники сайта для просмотра и выставления точек отстановки кода. | ||
|
||
### Оставнока и продолжение выполнения кода |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
js/debugging/index.md
Outdated
Просто остановка | ||
Остановка по условию | ||
|
||
Step over line of code |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@alexbaumgertner прйти на помощь? |
@nlopin да, спасибо! |
@nlopin статья еще актуальна? Хочу вернуться к ней и закончить. |
Привет! Конечно актуальна 👍 |
@alexbaumgertner будем тут допиливать?) Я могу как-то помочь? |
Да, мне нужна помощь с примерами отладки в браузере |
🔥 Замечательно |
Можно созвониться на выходных и парно попрограммировать |
@HellSquirrel Завтра, 10 декабря вечером тебе удобно? |
@alexbaumgertner сори что поздно сюда зашла. Давай попробуем след. выходные или любое удобное тебе время, начиная с четверга :) |
В выходные будет ок! Я начал добавлять примеры и скриншоты. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Крутое начало ❤️
Если парно попраграммировать все еще актуально, выбирай слотик на выхах и поехали
https://calendly.com/polina_gurtovaya/pair-programming-on-weekends?month=2022-12
js/debugging/index.md
Outdated
Сначала определимся с тем, что мы ищем в коде. | ||
Баги в программе могут быть двух видов – запуск программы аварийно завершается ошибкой или программа выдает неверные результаты. | ||
|
||
- В первом случае достаточно открыть консоль браузера и вы увидите название ошибки и строку кода, где произошло исключение (exception), вызвавшее остановку выполнения кода. Подробнее такие ошибки описаны в [Error и стандартные ошибки](/js/errors/) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
При наличии современных сборщиков, мы увидим все что угодно кроме строчки кода :(
Тут, кажется, надо рассказывать про сорс-мапы и всякие Sentry которые переписывают функции логирования. Или переформулировать предложение
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
js/debugging/index.md
Outdated
|
||
### Примеры | ||
|
||
#### Chrome |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Было бы хорошо упомянуть VSCode debugger
js/debugging/index.md
Outdated
![Инструменты разработчика Firefox, только консоль](images/dev-tools-console-john_firefox.png) | ||
|
||
### Оставнока и продолжение выполнения кода | ||
В devtools можно проставить точки остановки выполнения программы. Движок браузера встретив такую точку поставит выполнение кода на паузу и даст доступ к просмотру текущих значений переменных. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это почти так, но если более точно, мы можем смотреть stack-frames в которых лежат переменные
js/debugging/index.md
Outdated
|
||
|
||
#### Остановка по условию | ||
Добавленную в devtools точку остановки можно редактировать — задать остановку по условию: в поле ввода ввести выражение, возвращаемое значение true или false будет определять, останавливать или нет выполнение программы в этом месте. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Было бы здорово добавить и другие условия, например те что задаются из панели elements (правая кнопка + break on)
@alexbaumgertner, привет, кажется, намечается крутая статья 👀 Хочу обратить твоё внимание, что в Доке принято писать один абзац в одной строке, потому что парсер, когда видит перенос строки, вставляет |
|
||
#### Стек вызовов | ||
TODO: добавить пояснение | ||
js/async-in-js/index.md |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- отладка асинхронного кода https://developer.chrome.com/blog/async-call-stack/
@alexbaumgertner приветик. Надо помогать?) |
Да, я застрял на примере. |
@@ -0,0 +1,62 @@ | |||
/** |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@HellSquirrel посмотри пожалуйста пример
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Привет, полезная должна получиться статья! Есть пара предложений
* Пример отладки асинхронного кода | ||
* */ | ||
|
||
(async function () { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Что думаешь про использование top level await? Должно работать во всех браузерах https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#browser_compatibility
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я бы оставила как есть. Top level await не очень хорошо пока в нодике работает. На случай если будут переносить
async function getNetSalary (salaryGross) { | ||
const taxValueRealResult = await getTaxValueReal('AB') | ||
|
||
if (!taxValueRealResult.error) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ДУмаю что лаконичнее будет обойтись без отрицания, как считаешь?
if (!taxValueRealResult.error) { | |
if (taxValueRealResult.data) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут надо аккуратно, если taxValueRealResult.data = 0, то код сломается.
|
||
return netSalary | ||
} else { | ||
return Promise.reject(taxValueRealResult.error) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Альтернативный синтаксис:
return Promise.reject(taxValueRealResult.error) | |
throw taxValueRealResult.error |
|
||
console.log("Зарплата после налогов: ", netSalary); | ||
} catch (error) { | ||
console.warn("Ошибка при вычислении зарплаты после налогов: ", error); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вижу что где-то есть ;
, а где-то нет. У редакции есть правила на форматирование кода?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я форматирую своим prettier. Специальных требований нет
|
||
#### Пример подключения к NodeJS отладчику | ||
|
||
Chrome позволяет подключаться к [NodeJS рантайму](https://nodejs.org/en/docs/guides/debugging-getting-started/#command-line-options) и выполнять отладку в средствах разработчика. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Думаю что кроме command-line-options есть еще смысл оставить ссылку на #inspector-clients чтобы у читателя была информация как подключиться дебаггером к процессу.
Превью контента из b802587 опубликовано. |
Пока закрываю этот PR, @alexbaumgertner приходи переоткрывать, если найдутся силы :) Я с удовольствием помогу тебе закончить статью :) |
fixes #375