db-errors icon indicating copy to clipboard operation
db-errors copied to clipboard

Feature request: highlight the SQL in the error message

Open capaj opened this issue 5 years ago • 0 comments

I think it would be really cool, if the error message would be colored, so it can be read a bit better in the terminal. I have a proof of concept running, and the output in Jest looks like this:

  • for syntax error

image

  • for prepared statement parameter count mismatch: image

which is night and day compared to the current messages without any highlighting. My implementation is super naive based on https://github.com/Vincit/objection.js/pull/1621#issuecomment-567220373

  async execute() {
    let p
    try {
      p = await super.execute()
    } catch (err) {
      if (this._asyncStack) {
        const originalStack = err.stack.split('\n').slice(7)

        const newStack: string = originalStack
          .concat(this._asyncStack)
          .join('\n')

        const nativeErrPosition = Number(err.nativeError?.position)
        if (nativeErrPosition) {
          const offset = -1
          const { message } = err
          const beforeSyntaxErr = highlight(
            message.substring(0, nativeErrPosition + offset),
            {
              language: 'sql',
              ignoreIllegals: true
            }
          )
          const withSytaxErrorHighlighted =
            beforeSyntaxErr +
            chalk.blue.bgRed.bold(
              message.substring(
                nativeErrPosition + offset,
                nativeErrPosition + offset + 1
              )
            ) +
            chalk.yellow(
              message.substring(nativeErrPosition + offset + 1, message.length)
            )
          err.message = withSytaxErrorHighlighted
        } else if (err instanceof DBError) {
          err.message = highlight(err.message, {
            language: 'sql',
            ignoreIllegals: true
          })
        }
        err.stack = newStack
      }
      throw err
    }
    return p
  }

capaj avatar Mar 07 '20 01:03 capaj