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 经典实例:第三版
错误和测试
267
以捕获标准的
Error
对象,然后使用
instanceof
检查
错误类型,编写条件代码处
理不同的类型。如果采用这种方式,务必小心,不要意外抑制你无法处理的错误。
在本节的示例中,明显可以看出,我们处理了
RangeError
TypeError
类型。除
此之外,我们假定自己无能为力,无法解决问题,使用
throw
语句重新抛出错误。
throw
语句的作用是再次抛出同样的错误。如果是函数内的代码,错误将沿着堆栈
一直向上冒泡,直至找到能正确处理错误的代码。如果没有被任何错误处理结构捕
获,则变成未处理的错误,这跟一开始就没有捕获错误的效果是一样的。(未处理
的错误在
10.4
节进一步说明。)
换句话说就是,重新抛出未知错误的行为与只捕获特定类型的异常是一样的。可惜
JavaScript
语言不支持直接捕获特定类型的异常,否则也不用这么麻烦。
10.2.4
参考
10.6
节介绍如何自定义错误类表示特定的错误状况,并传递关于错误的额外信息。
10.3
捕获异步错误
10.3.1
问题
你想为在后台线程中执行的有风险的操作添加错误处理功能。
10.3.2
方案
JavaScript
中各种异步
API
采用不同的模型,具体如何处理错误取决于你使用的函数。
对于较旧的
API
,可能需要提供一个回调函数,在出错时调用,或者依附一个事件
处理函数。
XMLHttpRequest
对象提供一个
error
事件,在请求失
败时通知你,例如
下面的代码。
const
request =
new
XMLHttpRequest();
request.onerror ...
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