在 JavaScript 中将错误对象转换为字符串
Convert an Error Object to a String in JavaScript
要将错误对象转换为字符串,请访问该message
对象的属性,例如err.message
. 该message
属性是对错误发生原因的人类可读描述。
const err = new Error('Something went wrong'); console.log(err.message); // 👉️ "Something went wrong"
当使用
Error()
构造函数创建错误时,我们可以访问错误的
message
属性以获取错误发生原因的人类可读字符串。
Error()
造函数或从中扩展的情况下抛出错误。最佳实践是始终使用错误构造函数抛出错误,或者在需要添加功能时扩展它。
throw new Error('Something went wrong'); Promise.reject(new Error('Something went wrong'));
即使在拒绝承诺时,您也可以将错误传递给reject()
方法。
如果你必须处理来自第三方包的错误的奇怪实现,你应该检查错误值是否是一个对象并且具有message
避免访问不存在的属性的属性。
const err = null; if (typeof err === 'object' && err !== null && 'message' in err) { const message = err.message; console.log(message); }
我们的if
条件使用逻辑与 (&&) 运算符,因此if
要运行该块,必须满足所有条件。
err
变量是否存储了具有对象类型的值,因为错误具有对象类型。Then we check if the variable is not equal to null
. Unfortunately, if you
check the type of null – console.log(typeof null)
, you will get an "object"
value back, so we have to make sure the value is not null
.
message
property.Then we know we can safely access the message
property on the object.
If that doesn’t work, as a last resort, you can try to access the toString()
method on the error object.
Some third party packages throw error objects that implement the toString()
method.
const err = null; if (typeof err === 'object' && err !== null && 'toString' in err) { const message = err.toString(); console.log(message); }
If that doesn’t work either, you have to console.log
the error object and
investigate what properties and methods it implements.