其他分享
首页 > 其他分享> > [Typescript] Toolbox: isError

[Typescript] Toolbox: isError

作者:互联网

function isError(err: any): err is Error {
  return err instanceof Error;
}

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

 

You can also have the following in test case, but do NOT put into production:

function assertIsError(err: any): asserts err is Error {
  if(!(err instanceof Error)) throw new Error(`Not an error: ${err}`);
}

try {
  somethingRisky();
} catch(err: unknown) {
  // in a test case, you expect `err` must be an Error type
  // if not, throw Error  
  assertIsError(err);
  console.log(err.stack)
}

 

标签:Typescript,console,log,err,any,Error,Toolbox,isError
来源: https://www.cnblogs.com/Answer1215/p/16619772.html