我过去三年从事Swift开发,最近改用打字稿。
在Swift中,NSError类型的错误为我们提供了一些属性。
在JavaScript中,有任何错误。
为什么有错误?如何创建具有某些属性的自定义类并在整个项目中使用它?
try {
const decodedResult = decode(token)
// Adding userId in the headers to use in the models.
req.headers.userId = decodedResult.paylod.id
next()
} catch (error) {
console.log(error)
new errorController(401, 'Authentication required.', res)
}
现在,错误对象的类型为any。我希望它是强类型的。
任何类型都是我们在编写应用程序时都不知道的变量类型。这些值可能来自动态内容,例如来自用户或第三方库。在这些情况下,我们要选择退出类型检查,并让值通过编译时检查。为此,我们将它们标记为any类型。
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
您可以Error
在Typescript中扩展Class以创建自定义错误处理程序
class MyError extends Error {
constructor(m: string) {
super(m);
}
anyFunction() {
return "Hello World " ;
}
}
try {
const decodedResult = decode(token)
// Adding userId in the headers to use in the models.
req.headers.userId = decodedResult.paylod.id
next()
} catch (error) {
console.log(error)
throw new MyError() // pass arguments of constructor if any
}
请参阅参考
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句