文章内容

2022/1/11 18:33:01,作 者: 黄兵

Javascript ?? 实际使用中的一些总结


最近在编写 Angular 程序的时候遇到这样一个问题,系统抛出的错误与自己定义抛出的错误不一样,需要根据情况进行判断,自己前端捕捉到的错误代码如下:

getAllBlogTags() {
this.isLoading$.next(true);
this.sub = this.blogService.getAllBlogTags().subscribe(res => {
this.dataSource = res;
}, error => {
console.log(error);
this.snackBar.open(error.error.message , '关 闭', {
horizontalPosition: 'start',
verticalPosition: 'bottom',
});
}, () => {
this.isLoading$.next(false);
});
}

通过查看控制台,可以看到如果是后端框架默认爬虫错误信息内容如下:

  1. error"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>404 Not Found</title>\n<h1>Not Found</h1>\n<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>\n"
  2. message"Http failure response for http://localhost:4200/api/v1/blog/tags: 404 NOT FOUND"
  3. name"HttpErrorResponse"
  4. okfalse
  5. status404
  6. statusText"NOT FOUND"
  7. url"http://localhost:4200/api/v1/blog/tags"

通过上面的代码明显无法显示错误信息,但是通过修改代码换成 ?? 却可以解决问题:

getAllBlogTags() {
this.isLoading$.next(true);
this.sub = this.blogService.getAllBlogTags().subscribe(res => {
this.dataSource = res;
}, error => {
console.log(error);
this.snackBar.open(error.error.message ?? error.message, '关 闭', {
horizontalPosition: 'start',
verticalPosition: 'bottom',
});
}, () => {
this.isLoading$.next(false);
});
}

代码解释:

error.error.message ?? error.message

双问号 ?? 的操作符跟 || 类似,如果给定变量值为 null 或者 undefined,刚使用双问号后的默认值,否则使用该变量值。

下面是一些具体的操作示例:

undefined ?? 'default'
'default'

null ?? 'default'
'default'

false ?? 'default'
false

'' ?? 'default'
''

0 ?? 'default'
0


参考资料:

1、ES新提案:双问号操作符


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Javascript ?? 实际使用中的一些总结

分享到:

发表评论

评论列表