chore(medusa): Move formatException to the errorHandler to be always applied and not have to apply it manually (#2467)

**What**

Move the usage of the formatException to the errorHandler level in order to not have to try catch here and there to apply it. Also make our error handling uniformed and avoid forgetting to apply it.

FIXES CORE-721
This commit is contained in:
Adrien de Peretti
2022-10-19 16:22:42 +00:00
committed by GitHub
parent fcfb7d167b
commit 2f00bd100a
8 changed files with 184 additions and 201 deletions
@@ -1,6 +1,7 @@
import { NextFunction, Request, Response } from "express" import { NextFunction, Request, Response } from "express"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { Logger } from "../../types/global" import { Logger } from "../../types/global"
import { formatException } from "../../utils";
const QUERY_RUNNER_RELEASED = "QueryRunnerAlreadyReleasedError" const QUERY_RUNNER_RELEASED = "QueryRunnerAlreadyReleasedError"
const TRANSACTION_STARTED = "TransactionAlreadyStartedError" const TRANSACTION_STARTED = "TransactionAlreadyStartedError"
@@ -18,6 +19,9 @@ export default () => {
next: NextFunction next: NextFunction
) => { ) => {
const logger: Logger = req.scope.resolve("logger") const logger: Logger = req.scope.resolve("logger")
err = formatException(err)
logger.error(err) logger.error(err)
const errorType = err.type || err.name const errorType = err.type || err.name
+28 -21
View File
@@ -10,7 +10,6 @@ import { FindConfig, Selector } from "../types/common"
import { CustomerGroupUpdate } from "../types/customer-groups" import { CustomerGroupUpdate } from "../types/customer-groups"
import { import {
buildQuery, buildQuery,
formatException,
isDefined, isDefined,
isString, isString,
PostgresError, PostgresError,
@@ -108,26 +107,8 @@ class CustomerGroupService extends TransactionBaseService {
) )
return await cgRepo.addCustomers(id, ids) return await cgRepo.addCustomers(id, ids)
}, },
async (error: any) => { async (e: any) => {
if (error.code === PostgresError.FOREIGN_KEY_ERROR) { await this.handleCreationFail(id, ids, e)
await this.retrieve(id)
const existingCustomers = await this.customerService_.list({
id: ids,
})
const nonExistingCustomers = ids.filter(
(cId) => existingCustomers.findIndex((el) => el.id === cId) === -1
)
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`The following customer ids do not exist: ${JSON.stringify(
nonExistingCustomers.join(", ")
)}`
)
}
throw formatException(error)
} }
) )
} }
@@ -274,6 +255,32 @@ class CustomerGroupService extends TransactionBaseService {
return customerGroup return customerGroup
} }
private async handleCreationFail(
id: string,
ids: string[],
error: any
): Promise<never> {
if (error.code === PostgresError.FOREIGN_KEY_ERROR) {
await this.retrieve(id)
const existingCustomers = await this.customerService_.list({
id: ids,
})
const nonExistingCustomers = ids.filter(
(cId) => existingCustomers.findIndex((el) => el.id === cId) === -1
)
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`The following customer ids do not exist: ${JSON.stringify(
nonExistingCustomers.join(", ")
)}`
)
}
throw error
}
} }
export default CustomerGroupService export default CustomerGroupService
+4 -8
View File
@@ -10,7 +10,6 @@ import { CustomerRepository } from "../repositories/customer"
import { AddressCreatePayload, FindConfig, Selector } from "../types/common" import { AddressCreatePayload, FindConfig, Selector } from "../types/common"
import { CreateCustomerInput, UpdateCustomerInput } from "../types/customers" import { CreateCustomerInput, UpdateCustomerInput } from "../types/customers"
import { buildQuery, isDefined, setMetadata } from "../utils" import { buildQuery, isDefined, setMetadata } from "../utils"
import { formatException } from "../utils/exception-formatter"
import EventBusService from "./event-bus" import EventBusService from "./event-bus"
type InjectedDependencies = { type InjectedDependencies = {
@@ -19,6 +18,7 @@ type InjectedDependencies = {
customerRepository: typeof CustomerRepository customerRepository: typeof CustomerRepository
addressRepository: typeof AddressRepository addressRepository: typeof AddressRepository
} }
/** /**
* Provides layer to manipulate customers. * Provides layer to manipulate customers.
*/ */
@@ -301,8 +301,7 @@ class CustomerService extends TransactionBaseService {
customerId: string, customerId: string,
update: UpdateCustomerInput update: UpdateCustomerInput
): Promise<Customer> { ): Promise<Customer> {
return await this.atomicPhase_( return await this.atomicPhase_(async (manager) => {
async (manager) => {
const customerRepository = manager.getCustomRepository( const customerRepository = manager.getCustomRepository(
this.customerRepository_ this.customerRepository_
) )
@@ -346,12 +345,9 @@ class CustomerService extends TransactionBaseService {
await this.eventBusService_ await this.eventBusService_
.withTransaction(manager) .withTransaction(manager)
.emit(CustomerService.Events.UPDATED, updated) .emit(CustomerService.Events.UPDATED, updated)
return updated return updated
}, })
async (error) => {
throw formatException(error)
}
)
} }
/** /**
-5
View File
@@ -37,7 +37,6 @@ import {
} from "../types/discount" } from "../types/discount"
import { buildQuery, setMetadata } from "../utils" import { buildQuery, setMetadata } from "../utils"
import { isFuture, isPast } from "../utils/date-helpers" import { isFuture, isPast } from "../utils/date-helpers"
import { formatException } from "../utils/exception-formatter"
import { FlagRouter } from "../utils/flag-router" import { FlagRouter } from "../utils/flag-router"
import CustomerService from "./customer" import CustomerService from "./customer"
import DiscountConditionService from "./discount-condition" import DiscountConditionService from "./discount-condition"
@@ -200,7 +199,6 @@ class DiscountService extends TransactionBaseService {
"Fixed discounts can have one region" "Fixed discounts can have one region"
) )
} }
try {
if (discount.regions) { if (discount.regions) {
discount.regions = (await Promise.all( discount.regions = (await Promise.all(
discount.regions.map(async (regionId) => discount.regions.map(async (regionId) =>
@@ -230,9 +228,6 @@ class DiscountService extends TransactionBaseService {
} }
return result return result
} catch (error) {
throw formatException(error)
}
}) })
} }
@@ -15,7 +15,6 @@ import {
PriceListPriceUpdateInput, PriceListPriceUpdateInput,
UpdatePriceListInput, UpdatePriceListInput,
} from "../types/price-list" } from "../types/price-list"
import { formatException } from "../utils/exception-formatter"
import ProductService from "./product" import ProductService from "./product"
import RegionService from "./region" import RegionService from "./region"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
@@ -119,7 +118,6 @@ class PriceListService extends TransactionBaseService {
const { prices, customer_groups, includes_tax, ...rest } = priceListObject const { prices, customer_groups, includes_tax, ...rest } = priceListObject
try {
const rawPriceList: DeepPartial<PriceList> = { const rawPriceList: DeepPartial<PriceList> = {
...rest, ...rest,
} }
@@ -150,9 +148,6 @@ class PriceListService extends TransactionBaseService {
return await this.retrieve(priceList.id, { return await this.retrieve(priceList.id, {
relations: ["prices", "customer_groups"], relations: ["prices", "customer_groups"],
}) })
} catch (error) {
throw formatException(error)
}
}) })
} }
@@ -10,7 +10,6 @@ import {
UpdateProductCollection, UpdateProductCollection,
} from "../types/product-collection" } from "../types/product-collection"
import { buildQuery, isString, setMetadata } from "../utils" import { buildQuery, isString, setMetadata } from "../utils"
import { formatException } from "../utils/exception-formatter"
import EventBusService from "./event-bus" import EventBusService from "./event-bus"
type InjectedDependencies = { type InjectedDependencies = {
@@ -113,12 +112,8 @@ class ProductCollectionService extends TransactionBaseService {
this.productCollectionRepository_ this.productCollectionRepository_
) )
try {
const productCollection = collectionRepo.create(collection) const productCollection = collectionRepo.create(collection)
return await collectionRepo.save(productCollection) return await collectionRepo.save(productCollection)
} catch (error) {
throw formatException(error)
}
}) })
} }
@@ -183,7 +178,6 @@ class ProductCollectionService extends TransactionBaseService {
return await this.atomicPhase_(async (manager) => { return await this.atomicPhase_(async (manager) => {
const productRepo = manager.getCustomRepository(this.productRepository_) const productRepo = manager.getCustomRepository(this.productRepository_)
try {
const { id } = await this.retrieve(collectionId, { select: ["id"] }) const { id } = await this.retrieve(collectionId, { select: ["id"] })
await productRepo.bulkAddToCollection(productIds, id) await productRepo.bulkAddToCollection(productIds, id)
@@ -191,9 +185,6 @@ class ProductCollectionService extends TransactionBaseService {
return await this.retrieve(id, { return await this.retrieve(id, {
relations: ["products"], relations: ["products"],
}) })
} catch (error) {
throw formatException(error)
}
}) })
} }
-5
View File
@@ -32,7 +32,6 @@ import {
UpdateProductInput, UpdateProductInput,
} from "../types/product" } from "../types/product"
import { buildQuery, isDefined, setMetadata } from "../utils" import { buildQuery, isDefined, setMetadata } from "../utils"
import { formatException } from "../utils/exception-formatter"
import EventBusService from "./event-bus" import EventBusService from "./event-bus"
type InjectedDependencies = { type InjectedDependencies = {
@@ -362,7 +361,6 @@ class ProductService extends TransactionBaseService {
rest.discountable = false rest.discountable = false
} }
try {
let product = productRepo.create(rest) let product = productRepo.create(rest)
if (images?.length) { if (images?.length) {
@@ -414,9 +412,6 @@ class ProductService extends TransactionBaseService {
id: result.id, id: result.id,
}) })
return result return result
} catch (error) {
throw formatException(error)
}
}) })
} }
@@ -4,7 +4,7 @@ export enum PostgresError {
DUPLICATE_ERROR = "23505", DUPLICATE_ERROR = "23505",
FOREIGN_KEY_ERROR = "23503", FOREIGN_KEY_ERROR = "23503",
} }
export const formatException = (err): Error => { export const formatException = (err): MedusaError => {
switch (err.code) { switch (err.code) {
case PostgresError.DUPLICATE_ERROR: case PostgresError.DUPLICATE_ERROR:
return new MedusaError( return new MedusaError(