Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
262
10
错误和测试
代码错误不可避免。通常,错误是可以预期的。与外部资源(例如文件、数据库或
Web
服务器
API
)交互的操作往往存在风险。从代码外部获取的信息,不管是从网
页表单中读取,还是从其他库接收,都有可能存在错误,或者不同于预期的形式。
但是,老话说得好,错误不可怕,就看你如何处理错误。
那么,我们应该怎么处理错误呢?
JavaScript
的默认行为是在出错的位置崩溃,悄
无声息地向控制台输出堆栈跟踪。不过,也有更好的处理方式。你可以捕获错误,
做出反应,也可以修改之后再次抛出,如果你愿意,甚至可以置之不理。与很多其
他语言相比,
JavaScript
的错误处理功能相对简陋。但是,基本的错误处理功能还是
很重要的,本章的很多经典实例就专注这个任务。
防御错误是肯定要做的,不过避免错误发生同样重要。在这方面,有很多支持
JavaScript
的测试框架,包括
Jest
Mocha
Jasmine
Karma
。你可以借助这些框
架编写单元测试,确保代码能按预期执行。本章将简要介绍
Jest
10.1
捕获并压制错误
10.1.1
问题
你执行的任务可能失败,你不想让错误中断代码,也不希望错误出现在开发者控制
台中。
错误和测试
263
10.1.2
方案
把可能失败的代码放
try...catch
中,如下所示。 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov
JavaScript

JavaScript

David Flanagan
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9787519869601