Skip to content

TypeError: Cannot read property '2' of null #6725

Closed

Description

@abartolo

What you are doing?

Creating a record with the same value in a column that is Unique:true. I'm using FeathersJS with uses Sequelize. I successfully inserted new record via restful api using Postman. However if I send the same request again( create a user with the same email which the column is unique) it crashes the server with error "TypeError: Cannot read property '2' of null".

Below is the model I am using

// code here
const Sequelize = require('sequelize');

module.exports = function(sequelize) {
  const user = sequelize.define('users', {
    email: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true
    },
    password: {
      type: Sequelize.STRING,
      allowNull: false
    }
  }, {
    freezeTableName: true
  });

What do you expect to happen?

I expected to get a response back with an error stating its a duplicate or at least a clean error.

What is actually happening?

Crashed server since error wasn't caught.

Output, either JSON or SQL

image

Dialect: mysql
Database version: 5.7.13
Sequelize version: 3.24.4

Activity

  1. felixfbecker commented on Oct 19, 2016

    @felixfbecker
    Contributor

    That stack trace does not mention sequelize anywhere. If you still believe this is a sequelize bug, create an SSCCE. You can find a template here

  2. janmeier commented on Oct 20, 2016

    @janmeier
    Member

    @felixfbecker Actually it does ;), here

    @abartolo Which language is your mysql installation? Currently we only support parsing messages in english?

    In any case, we need a guard before accessing the match, checking if anything was actually matched

  3. felixfbecker commented on Oct 20, 2016

    @felixfbecker
    Contributor

    Sorry, overlooked that on the screenshot.

  4. abartolo commented on Oct 20, 2016

    @abartolo
    Author

    @janmeier Mysql is installed in english.

    So last night I tried to replicate the issue in my home environment since this was at work, and it worked! Sooo.... I assumed perhaps the installation of node_modules went wrong since my workplace has a lot of firewalls and strict security. But after reinstalled dependencies I still got the issue.

    The DB at my home env is 5.6.x and I doubt Mysql version is the issue so I looked at my node version found I'm using v4.2.1 @ work. This is a red flag since FeatherJS documentation is stating nodeV 5+ and if anything is below is required to use babel.

    Not sure if this is related to this issue but I will work on updating my node and see if that fixes the issue.

  5. janmeier commented on Oct 20, 2016

    @janmeier
    Member

    I'm actually pretty sure the mysql version is the issue then - We've had these kind of problems in the past where the error message as different between different versions of mysql.

    I think moving forward we should abstract the code that parses messages into a separate method that we can then easily unit test. There is no need to actually run tests against several different versions, but we'd like to be able to support them and at least not crash still :)

  6. added
    type: bug
    on Oct 20, 2016
  7. abartolo commented on Oct 20, 2016

    @abartolo
    Author

    @janmeier I can also confirm that mysql version is the issue. Luckily the mysql version locally installed at work is version 5.6.15 VS. the mysql 5.7.13 where I got this issue.

    I replicated both table structures and unique indexes as seen below. Sent a POST to create a new record and immediately sent the POST again to recreate the crash but this time the server did not crash and instead got a JSON error as expected.

    Expected Response with mysql version 5.6.15
    { "test_description": "b2b_edgeFlow_creditCard_visa_splitpayment_3", "status": "failed", "build_date": "2016-08-01 15:20:28" }

    Both have the same Table and Indexes
    image

    Indexes
    image

  8. janmeier commented on Oct 24, 2016

    @janmeier
    Member

    Could you post the different error messages?

  9. janmeier commented on Oct 24, 2016

    @janmeier
    Member

    I mean that actually error messages from MySQL - so the code can be fixed to support both

  10. crzidea commented on Dec 22, 2016

    @crzidea

    I got the exactly issue with this. Any update?

  11. janmeier commented on Dec 22, 2016

    @janmeier
    Member

    @crzidea Some details please? Which mysql version, and what is the wording of the message? As i've already mentioned before we need to know the actual wording of the error message to be able to support it

  12. akhoury commented on Apr 20, 2018

    @akhoury

    this is till happening when I try to update a record with a column (that is set to unique:true) with a non unique value,

    sequelize v4.28.6
    node v9.2.0
    mysql 5.7.21
    
    /Users/user/code/backend/node_modules/sequelize/lib/dialects/mysql/query.js:186
            const uniqueKey = this.model && this.model.uniqueKeys[match[2]];
                                                                       ^
    
    TypeError: Cannot read property '2' of null
        at Query.formatError (/Users/user/code/backend/node_modules/sequelize/lib/dialects/mysql/query.js:186:68)
        at Query.connection.query [as onResult] (/Users/user/code/backend/node_modules/sequelize/lib/dialects/mysql/query.js:55:23)
        at Query.Command.execute (/Users/user/code/backend/node_modules/mysql2/lib/commands/command.js:30:12)
        at Connection.handlePacket (/Users/user/code/backend/node_modules/mysql2/lib/connection.js:515:28)
        at PacketParser.onPacket (/Users/user/code/backend/node_modules/mysql2/lib/connection.js:94:16)
        at PacketParser.executeStart (/Users/user/code/backend/node_modules/mysql2/lib/packet_parser.js:77:14)
        at Socket.<anonymous> (/Users/user/code/backend/node_modules/mysql2/lib/connection.js:102:29)
        at Socket.emit (events.js:159:13)
        at addChunk (_stream_readable.js:265:12)
        at readableAddChunk (_stream_readable.js:252:11)
        at Socket.Readable.push (_stream_readable.js:209:10)
        at TCP.onread (net.js:598:20)
  13. akhoury commented on Apr 21, 2018

    @akhoury

    The issue is here:

    case 1062: {
    const match = err.message.match(/Duplicate entry '(.*)' for key '?((.|\s)*?)'?$/);
    let fields = {};
    let message = 'Validation error';
    const values = match ? match[1].split('-') : undefined;
    const uniqueKey = this.model && this.model.uniqueKeys[match[2]];
    if (uniqueKey) {
    if (uniqueKey.msg) message = uniqueKey.msg;
    fields = _.zipObject(uniqueKey.fields, values);
    } else {
    fields[match[2]] = match[1];
    }

    I put a log statement to see the err and it looks like this.

    {
      "code": "ER_DUP_ENTRY",
      "errno": 1062,
      "sqlState": "23000",
      "sqlMessage": "",
      "sql": "INSERT INTO `users` (`id`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'[email protected]','$2a$10$0yoLkp7LQD.IcHFfNCib..hL8LeM/soCUdSuOF1c1.NGHjeF8nNbO','2018-04-21 08:52:42','2018-04-21 08:52:42');"
    }

    There is no err.message so match is null, and there are 2 statements that don't guard against it.

            const uniqueKey = this.model && this.model.uniqueKeys[match[2]];

    and

              fields[match[2]] = match[1];

    I am using MySQL 5.7.21

  14. Wadeck commented on Aug 16, 2018

    @Wadeck

    Same error here, using MySQL in french, exception is "Duplicata du champ 'UC....-UC....-xxx' pour la clef '<key_name> etc.

    The approach to use the translated name in the trace does not seem really stable :(

  15. zhangshichun commented on Jan 5, 2019

    @zhangshichun
    Contributor

    this is because that:
    you save a data like 'cccc\r',so the err.message is ''Duplicate entry 'cccc\r' for key ...",then,the method match return null.
    please replace('\r','') before you create()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    staletype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions