zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript Unit testing] Error Handling with Unknown

typescript Error with Testing unknown unit Handling
2023-09-14 08:59:13 时间
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)
}