Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(medusa): Improve database loader error handling #4254

Merged
merged 6 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sharp-melons-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@medusajs/medusa": patch
---

chore(medusa): Improve database loader error handling
28 changes: 5 additions & 23 deletions packages/medusa/src/loaders/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from "typeorm"
import { ConfigModule } from "../types/global"
import "../utils/naming-strategy"
import { handlePostgresDatabaseError } from "@medusajs/utils"

type Options = {
configModule: ConfigModule
Expand Down Expand Up @@ -52,33 +53,14 @@ export default async ({
(configModule.projectConfig.database_logging || false),
} as DataSourceOptions)

try {
await dataSource.initialize()
} catch (err) {
// database name does not exist
if (err.code === "3D000") {
throw new Error(
`Specified database does not exist. Please create it and try again.\n${err.message}`
)
}

throw err
}
await dataSource.initialize().catch(handlePostgresDatabaseError)

// If migrations are not included in the config, we assume you are attempting to start the server
// Therefore, throw if the database is not migrated
if (!dataSource.migrations?.length) {
try {
await dataSource.query(`select * from migrations`)
} catch (err) {
if (err.code === "42P01") {
throw new Error(
`Migrations missing. Please run 'medusa migrations run' and try again.`
)
}

throw err
}
await dataSource
.query(`select * from migrations`)
.catch(handlePostgresDatabaseError)
}

return dataSource
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import {
DatabaseErrorCode,
handlePostgresDatabaseError,
} from "../handle-postgres-database-error"
import { EOL } from "os"

describe("handlePostgresDataError", function () {
it("should throw a specific message on database does not exists", function () {
const error = new Error("database does not exist")
Object.assign(error, { code: DatabaseErrorCode.databaseDoesNotExist })

let outputError: any
try {
handlePostgresDatabaseError(error)
} catch (e) {
outputError = e
}

expect(outputError.message).toEqual(
`The specified PostgreSQL database does not exist. Please create it and try again.${EOL}${error.message}`
)
})

it("should throw a specific message on database connection failure", function () {
const error = new Error("database does not exist")
Object.assign(error, { code: DatabaseErrorCode.connectionFailure })

let outputError: any
try {
handlePostgresDatabaseError(error)
} catch (e) {
outputError = e
}

expect(outputError.message).toEqual(
`Failed to establish a connection to PostgreSQL. Please ensure the following is true and try again:
- You have a PostgreSQL database running
- You have passed the correct credentials in medusa-config.js
- You have formatted the database connection string correctly. See below:
"postgres://[username]:[password]@[host]:[post]/[db_name]" - If there is no password, you can omit it from the connection string
${EOL}
${error.message}`
)
})

it("should throw a specific message on database wrong credentials", function () {
const error = new Error("database does not exist")
Object.assign(error, { code: DatabaseErrorCode.wrongCredentials })

let outputError: any
try {
handlePostgresDatabaseError(error)
} catch (e) {
outputError = e
}

expect(outputError.message).toEqual(
`The specified credentials does not exists for the specified PostgreSQL database.${EOL}${error.message}`
)
})

it("should throw a specific message on database not found", function () {
const error = new Error("database does not exist")
Object.assign(error, { code: DatabaseErrorCode.notFound })

let outputError: any
try {
handlePostgresDatabaseError(error)
} catch (e) {
outputError = e
}

expect(outputError.message).toEqual(
`The specified connection string for your PostgreSQL database might have illegal characters. Please check that it only contains allowed characters [a-zA-Z0-9]${EOL}${error.message}`
)
})

it("should throw a specific message on database migration missing", function () {
const error = new Error("database does not exist")
Object.assign(error, { code: DatabaseErrorCode.migrationMissing })

let outputError: any
try {
handlePostgresDatabaseError(error)
} catch (e) {
outputError = e
}

expect(outputError.message).toEqual(
`Migrations missing. Please run 'medusa migrations run' and try again.`
)
})

it("should re throw unhandled error code", function () {
const error = new Error("database does not exist")
Object.assign(error, { code: "test" })

let outputError: any
try {
handlePostgresDatabaseError(error)
} catch (e) {
outputError = e
}

expect(outputError.message).toEqual("database does not exist")
})
})
49 changes: 49 additions & 0 deletions packages/utils/src/common/handle-postgres-database-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { EOL } from "os"

export const DatabaseErrorCode = {
databaseDoesNotExist: "3D000",
connectionFailure: "ECONNREFUSED",
wrongCredentials: "28000",
notFound: "ENOTFOUND",
migrationMissing: "42P01",
}

export function handlePostgresDatabaseError(err: any): never {
if (DatabaseErrorCode.databaseDoesNotExist === err.code) {
throw new Error(
`The specified PostgreSQL database does not exist. Please create it and try again.${EOL}${err.message}`
)
}

if (DatabaseErrorCode.connectionFailure === err.code) {
throw new Error(
`Failed to establish a connection to PostgreSQL. Please ensure the following is true and try again:
- You have a PostgreSQL database running
- You have passed the correct credentials in medusa-config.js
- You have formatted the database connection string correctly. See below:
"postgres://[username]:[password]@[host]:[post]/[db_name]" - If there is no password, you can omit it from the connection string
${EOL}
${err.message}`
)
}

if (DatabaseErrorCode.wrongCredentials === err.code) {
throw new Error(
`The specified credentials does not exists for the specified PostgreSQL database.${EOL}${err.message}`
)
}

if (DatabaseErrorCode.notFound === err.code) {
throw new Error(
`The specified connection string for your PostgreSQL database might have illegal characters. Please check that it only contains allowed characters [a-zA-Z0-9]${EOL}${err.message}`
)
}

if (DatabaseErrorCode.migrationMissing === err.code) {
throw new Error(
`Migrations missing. Please run 'medusa migrations run' and try again.`
)
}

throw err
}
1 change: 1 addition & 0 deletions packages/utils/src/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from "./medusa-container"
export * from "./set-metadata"
export * from "./wrap-handler"
export * from "./build-query"
export * from "./handle-postgres-database-error"