Node.js MySQL Error Handling

后端 未结 6 1785
遇见更好的自我
遇见更好的自我 2020-12-08 22:30

I\'ve read several examples for using mysql in node.js and I have questions about the error handling.

Most examples do error handling like this (perhaps for brevity)

6条回答
  •  爱一瞬间的悲伤
    2020-12-08 22:53

    In order to handle specific error handling cases that have returned from the sql connection you can look at the the 'error' object returned from the callback.

    so..

    const mysql = require('mysql') 
    
    let conn = mysql.createConnection(connConfig)
    
    conn.query(query, function(error, result, fields){
        if (error){
            console.log(typeof(error));
            for(var k in error){
                console.log(`${k}: ${error[k]}`)
            }
    }
    

    the console.log statement in the for loop above will output something like:

    object

    code: ER_TABLE_EXISTS_ERROR
    errno: 1050
    sqlMessage: Table 'table1' already exists
    sqlState: 42S01
    index: 0
    sql: CREATE TABLE table1 (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    City varchar(255)
    );
    

    using these keys you can pass off the values to a handler

提交回复
热议问题