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

 

上一篇:MYSQL数据库导入SQL报错 [Err] 1273 - Unknown collation: utf8mb4_0900_ai_ci


下一篇:Hessian远程服务调用问题之:unknown code