首页 > 其他 > 详细

[Typescript Unit testing] Error Handling with Unknown

时间:2020-11-15 23:11:02      阅读:38      评论:0      收藏:0      [点我收藏+]
function somethingRisky() {}

try {
    somethingRisky()
} catch(err: unknown) {
    if (err instanceof Error) {
        console.log(err.stack)
    } else {
    
       console.log(err)
    }
}

Force to handle edge cases.

 

Type assertion:

function somethingRisky() {}

// if err is an Error, then it is fine
// if not, then throw
function assertIsError(err: any): asserts err is Error {
    if (!(err istanceof Error)) throw new Error(`Not an error: ${err}`)
}

try {
    somethingRisky()
} catch(err: unknown) {
   assertIsError(err);
    console.log(err)
}

 

[Typescript Unit testing] Error Handling with Unknown

原文:https://www.cnblogs.com/Answer1215/p/13982892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!