/**
 * 表达式执行异常，将显示执行异常的位置信息
 */
export default class ExpressionException extends Error {
  constructor (source, pos, cause) {
    let message
    let beforeErrorContent = source.substring(0, pos).trim()
    const length = beforeErrorContent.length
    if (length > 1000) {
      beforeErrorContent = '以上省略......\n' + beforeErrorContent.substring(length - 1000)
    }
    const afterErrorContent = source.substring(pos)
    const afterErrorContentIndex = afterErrorContent.indexOf('\n')
    if (afterErrorContentIndex === -1) {
      message = beforeErrorContent.trim() + ' <- ' + afterErrorContent
    } else {
      message = beforeErrorContent.trim() + ' <- ' + afterErrorContent.substring(0, afterErrorContentIndex) + '\n后续省略......'
    }

    // 通过原生 Error 的 cause 参数传递原因
    super(message, { cause })
    this.name = this.constructor.name

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor)
    }
  }
}
