其他分享
首页 > 其他分享> > [Typescript Unit testing] Error Handling with Unknown

[Typescript Unit testing] Error Handling with Unknown

作者:互联网

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)
}

 

标签:function,Handling,console,log,err,Unknown,testing,somethingRisky,Error
来源: https://www.cnblogs.com/Answer1215/p/13982892.html