Error 错误处理
属性
1. Error: cause
- Error 实例中的 cause 数据属性指示导致该错误的具体原始原因。
try {
connectToDatabase()
} catch (err) {
throw new Error('Connecting to database failed.', { cause: err })
}
// 将结构化的数据作为 cause
function makeRSA(p, q) {
if (!Number.isInteger(p) || !Number.isInteger(q)) {
throw new Error('RSA key generation requires integer inputs.', {
cause: { code: 'NonInteger', values: [p, q] },
})
}
if (!areCoprime(p, q)) {
throw new Error('RSA key generation requires two co-prime integers.', {
cause: { code: 'NonCoprime', values: [p, q] },
})
}
// rsa algorithm…
}
2. Error.prototype.message
- message 属性是有关错误信息,人类易读的(human-readable)描述。
- 默认情况下,message 属性是一个空字符串,但是可以通过指定一段信息作为 Error constructor 的第一个参数创建一个实例来改变该属性值。
var e = new Error('Could not parse input') // e.message is "Could not parse input"
throw e
3. Error.prototype.name
- name 属性表示 error 类型的名称。初始值为"Error".
- 默认情况下,Error 对象的 name 属性值为"Error".name 属性和 message 属性一起,通过调用 Error.prototype.toString()方法,会作为最后异常信息的字符串表示。
抛出一个自定义错误
var e = new Error('Malformed input') // e.name 默认是"Error"
e.name = 'ParseError' // 修改之后,e.toString() 会成为下面这样的字符串
throw e // "ParseError: Malformed input"
二,方法
1. Error.prototype.toString()
- toString() 方法返回一个表示指定 Error 对象的字符串。
Error.prototype.toString = function () {
'use strict'
const obj = Object(this)
if (obj !== this) {
throw new TypeError()
}
let name = this.name
name = name === undefined ? 'Error' : String(name)
let msg = this.message
msg = msg === undefined ? '' : String(msg)
if (name === '') {
return msg
}
if (msg === '') {
return name
}
return name + ': ' + msg
}
const e1 = new Error('fatal error')
console.log(e1.toString()) // 'Error: fatal error'
const e2 = new Error('fatal error')
e2.name = undefined
console.log(e2.toString()) // 'Error: fatal error'
const e3 = new Error('fatal error')
e3.name = ''
console.log(e3.toString()) // 'fatal error'
const e4 = new Error('fatal error')
e4.name = ''
e4.message = undefined
console.log(e4.toString()) // ''
const e5 = new Error('fatal error')
e5.name = 'hello'
e5.message = undefined
console.log(e5.toString()) // 'hello'