I want to catch createConnection() Error #1998
Answered
by
wellwelwel
Philosoph228
asked this question in
Q&A
-
I want to handle connection error like this: import { Connection, createConnection } from 'mysql2';
let connection: Connection;
try {
connection = createConnection({
host: '127.0.0.1',
port: 3306,
user: 'root',
password: 'password'
});
} catch (err) {
if (err instanceof Error) {
console.log(`createConnection error: ${(err as Error).message}`);
}
throw err;
} But error doesn't catch. It just prints to console that it is uncaught:
|
Beta Was this translation helpful? Give feedback.
Answered by
wellwelwel
May 9, 2023
Replies: 1 comment
-
@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 import { Connection, createConnection } from 'mysql2/promise';
(async() => {
let connection: Connection;
try {
connection = await createConnection({
host: '127.0.0.1',
port: 3306,
user: 'root',
password: 'password',
});
} catch (err) {
if (err instanceof Error) {
console.log(`createConnection error: ${(err as Error).message}`);
}
}
})(); |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
sidorares
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Philosoph228, you can catch the errors adding an error event listener, like:
Or using
mysql/promise
, like: