Skip to content

I want to catch createConnection() Error #1998

Answered by wellwelwel
Philosoph228 asked this question in Q&A
Discussion options

You must be logged in to vote

@Philosoph228, you can catch the errors adding an error event listener, like:

import { Connection, createConnection } from 'mysql2';

let connection: Connection;

connection = createConnection({
   host: '127.0.0.1',
   port: 3306,
   user: 'root',
   password: 'password',
});

connection.addListener('error', (err) => {
   if (err instanceof Error) {
      console.log(`createConnection error: ${(err as Error).message}`);
   }
});

Or using mysql/promise, like:

import { Connection, createConnection } from 'mysql2/promise';

(async() => {
   let connection: Connection;
   
   try {   
      connection = await createConnection({
         host: '127.0.0.1',
         port: 3306,
         user: '…

Replies: 1 comment

Comment options

wellwelwel
May 9, 2023
Collaborator Sponsor

You must be logged in to vote
0 replies
Answer selected by sidorares
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants