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 经典实例:第三版
错误和测试
275
符串内容,发现不符合你制定的规则)。其他更具体的错误状况应该考虑自定义错
误类(
10.6
节)。
与很多较严格的语言相比,
JavaScript
很少使用错误。自己设计库时,最好也遵守这
个约定。遇到
JavaScript
正常容许的情况时(例如隐式类型转换),不要使用异常。
如果出现的状况不算异常,是正常操作中可能发生的情况,例如用户输入无效内容,
不要使用错误通知调用方。倘若是因为什么没有正确初始化而导致操作失败,代码
无法继续运行,那就要使用异常了。
10.5.4
参考
10.6
节说明如何自定义错误对象。
10.6
抛出自定义错误
10.6.1
问题
你想抛出自定义错误对象,表示特定的错误状况。
10.6.2
方案
创建一个类,继承自标准的
Error
类。构造函数应该接受一个描述性文本,用于设
message
属性,还要使用
super()
调用基类
Error
的构造函数,并传入消息。下
面自定义一个特别简单的错误类,然后抛出该类型的错误。
class
CustomError
extends
Error {
constructor(message) {
super
(message);
this
.name = 'CustomError';
//
可选的增强功能:如果支持的话,清理堆栈跟踪
if
(Error.captureStackTrace) {
Error.captureStackTrace(
this
, CustomError);
}
276
10
}
}
//
抛出这种错误试试 ...
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

JavaScript

T. J. Crowder
JavaScript

JavaScript

David Flanagan
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9787519869601