Steps to retrieve the primary key associated with a duplicate entry error (1062) in MySQL using the Knex.js library

Testing out the database by sending values from an HTML form has been successful so far. Unique inserts and good connections are working well. However, intentionally sending a duplicate username for testing purposes results in an error message - which is exactly what I want!

The challenge now is to extract the cause of the error, which happens to be the key. The error object looks like this when checked with typeof(error):

Error: Insert into Users (password, role, username) values ('1112131234434', 'basic', 'Cthulu') - Duplicate entry 'Cthulu' for key 'username'

  1. Attempting to extract the key after converting the object to JSON using JSON.stringify only gives part of the message: {"code":"ER_DUP_ENTRY","errno":1062,"sqlState":"#23000"} Missing is the other details needed. Is it not possible to convert the entire error to a string then perform a substring search for the key? Or am I approaching this problem incorrectly?

Additionally, trying to traverse through the keys of the object reveals that while it seems to be a string, it actually isn't. Extracting the specific part of the string as shown in "'key 'username'" from the error remains a challenge.

In essence, my aim is to send back the key 'username' to the client form indicating that their chosen username is already taken. The same process will later apply to the email, hence my need to identify and extract the key.

Edit: Considering implementing stored procedures with GET DIAGNOSTICS seems to be the next step. Following guidelines similar to this article might provide a solution.

Answer №1

It seems that I may not be the biggest fan of this solution, but it does work for me. What I did was create a stored procedure in MySQL using the GET DIAGNOSTICS command.

    DELIMITER //

    DROP PROCEDURE IF EXISTS `insert_new_user` //
    CREATE PROCEDURE `insert_new_user` (uname VARCHAR(45), pass CHAR(96), r varchar(15))
    BEGIN
        /**
        Return field that has triggered the error, otherwise, return good
        **/
     -- Declare variables to hold diagnostics area information
      DECLARE code CHAR(5) DEFAULT '00000';
      DECLARE msg TEXT;
      DECLARE rows INT;
      DECLARE result TEXT;
      -- Declare exception handler for failed insert
      DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
        BEGIN
          GET DIAGNOSTICS CONDITION 1
            code = RETURNED_SQLSTATE, msg = MESSAGE_TEXT;
        END;

      -- Perform the insert
      INSERT INTO Users(username, password, role) VALUES (uname, pass,  'full');

      -- Check whether the insert was successful
      IF code = '00000' THEN
        GET DIAGNOSTICS rows = ROW_COUNT;
        SET result = CONCAT('insert succeeded, row count = ',rows);
      ELSE
        SET result = CONCAT('insert failed, error = ',code,', message = ',msg);
      END IF;
      -- Display what happened
    SELECT result;

    END //

Although I modified the code slightly, I unfortunately can't recall the original source...

In my Express server, I utilized a knex.raw(...) statement. Then in the

.then(result => { ... })

function (since knex is a promise), I checked the result for errors by calling a getError(result) function. If an error is present, it provides me with the key, such as 'username'. (I still need to implement the alternative for no error) e.g.

---console output---for no errors

ERR_str: [[[{"result":"insert succeeded, row count = 1"}],{"fieldCount":0,"affectedRows":0,"insertId":0,"info":"","serverStatus":2,"warning.....it goes on

---end output-------

For reference, here is the console output when error 1062 occurs:

---console output---for 1062 error

ERR_str: [[[{"result":"insert failed, error = 23000, message = Duplicate entry 'leerman2' for key 'username'"}],{"fieldCount":0,"affectedRows":0,"insertId":0,"info":"","serverStatus":2,"warningStatus":0}],[[{"_b...it goes on

---end output-------

Below is the code for extracting the key:

    function getError(err) {
        const ERR_str = JSON.stringify(err);
        console.log(`Entered getError() function...proceeding to extract error...`);

        console.log(`ERR_str: ${ERR_str}`);
        console.log(`Error is string. [typeOf(ERR_str)]: ${typeof(ERR_str)}. (Attempting to extract key...`);
        const START = (ERR_str.indexOf('key')) + 'key'.length + 2; // 2 including spaces 
        console.log(`Start: ${START}`);
        const END = ERR_str.indexOf(`'"}`);
        console.log(`End: ${END}`);    
        const KEY = ERR_str.substr(START, END - START);
        console.log(`key to return to server: ${KEY}`);

        return KEY || 0;
    }

While not the most polished code, it serves as a solid starting point. I can now send it to Angular and continue working with it as intended. Any feedback on this approach is welcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are different ways to modify a bytearray within a file using angular js, whether it is an .xlsx or other

I received a bytearray response from my API that was converted from a .xlsx file. I now need to open or download this bytearray in the browser after converting it back to its original file extension. Can anyone provide guidance on how to achieve this? I ...

I need help figuring out how to send a POST/GET request from AJAX to a custom module controller in Odoo 10, but I'm running into issues

I have implemented a custom module in Odoo 10 with a simple controller. Everything works smoothly when accessing http://127.0.0.1:8069/cmodule/cmodule through the browser, displaying the expected return string. However, I encountered an issue when attempt ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...

Vue: Issue with Firebase Authentication REST API triggers 400 Bad Request Error

Here is the error message I am encountering: POST scheme https host identitytoolkit.googleapis.com filename /v1/accounts:signUp key AIzaSyAk1ueCLjDDWCNrt_23o5A4RCfeaYIlN6k Address 74.125.24.95:443 Status 400 Bad Request VersionHTTP/3 Transferred850 B ...

The null evaluation consistently yields a negative outcome

import org.json.JSONObject; String jsonData = "{\"someKey\": " + "null" + "}"; JSONObject jsonObject = new JSONObject(jsonData); Object key = jsonObject.get("someKey"); if (null == key) { ...

What is the reason for not modifying the filtered and sorted data?

I am currently working on implementing filter options for an item list, but I am facing an issue where the filtering does not work when selecting dropdown options. Array in App.jsx const cameraShowList=[ {id:1,model:"Canon",title:"Canon ...

Vertically arrange the table for better visibility

I need help with changing the table layout from horizontal to vertical. Currently, all fields are displayed horizontally and I want them to be displayed vertically. Also, I'm trying to add a functionality where the current date is added to the databas ...

Uploading multipart/form-data files in Angular with the $http module

I've encountered an issue that I need help with - despite the abundance of similar questions. Here's my problem: My goal is to transfer a file from an input field to a server using multipart/form-data I've attempted two different methods. ...

Vue Component, switching state

Feeling like I'm losing it, this should be really simple but it's not working... The idea is that when the link is clicked, the display property toggles between true and false. However, it's not working as expected. Vue.component('d ...

Ways to stop jQuery from stripping the <script> elements

Is there a way to stop jquery from removing my JS default behavior? function loadPageSuccess(data) { var data = $(data).find('#content'); alert($(data).html()); $("#content").html(data); $("#page").fadeTo(100,1); } function loadP ...

Inserting items into the document after updating the list with fresh data

I populate an array of objects when a button is clicked. The array only has 10 objects initially, but users can add more after it's loaded into the DOM. Here's how I handle this: $scope.Information = []; $.each(data, function (i, v) { if ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

Creating a constant in router resolve using AngularJS

Is there a way to define a constant in the router resolve and then use it within a controller by dependency injection? Whenever I try to run the project, an error shows up stating that the provider obj is unknown. var app = angular.module("pikadOnlineAp ...

Implementing a Countdown Clock in Auction Listings

Similar Question: Countdown to a specific date Is there a way to implement a jQuery countdown timer that starts from the day of posting an advertisement and ends on the expiry date? ...

"Encountering issues with logging in through AngularJS and the $http request functionality

My goal is to login using $http and GET of REST web services. This is my approach: Retrieve data based on username and password using $http.get Store the result in $scope.getResult=res; Assign variables to the retrieved data: var result=$scope.getResult ...

Encountering a FileNotFound Error when attempting to access a file in a different directory using Python

\parentDirectory \subdr1 -testfile.txt \subdr2 \childdir -data.json -config.pickle -jsonReader.py I am trying to access data.json from jsonReader.py in Python by using the following ...

Utilizing Airflow's web API to generate a JSON variable

Attempting to set up a variable with a JSON value in Airflow using the web API. Here is my script: curl -X POST "${AIRFLOW_URL}/api/v1/variables" \ -H "Content-Type: application/json" \ --user "${AIRFLOW_USERNAME}:${AIRFLOW_PASSW ...

There seems to be an issue with the bullet functionality in phaser.io

I'm having trouble firing a bullet from my object in my game. I have been struggling to find the proper reason for the issue. Here is a snippet of my code. Game.js var Game = { preload : function() { // spaceship image screen th ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...