@@ -3,15 +3,16 @@ import { useMutation } from "@tanstack/react-query";
33import { DateVO } from "@/lib/date/date" ;
44import { httpService } from "@/lib/http" ;
55import { Logger } from "@/lib/logger" ;
6+ import { UnknownError } from "@/lib/types/unknown-error" ;
67
7- interface IAddToCartValues {
8+ interface AddToCartPayload {
89 productId : number ;
910 quantity ?: number ;
1011 cartId : number ;
1112 userId : number ;
1213}
1314
14- interface IAddToCartDto {
15+ interface AddToCartDto {
1516 userId : number ;
1617 date : string ;
1718 products : { productId : number ; quantity : number } [ ] ;
@@ -21,33 +22,50 @@ export const useAddToCartMutation = () => {
2122 const { mutateAsync, isPending } = useMutation <
2223 void ,
2324 unknown ,
24- IAddToCartValues
25+ AddToCartPayload
2526 > ( {
2627 mutationFn : ( body ) =>
27- httpService . put < void , IAddToCartDto > ( `carts/${ body . cartId } ` , {
28+ httpService . put < void , AddToCartDto > ( `carts/${ body . cartId } ` , {
2829 userId : body . userId ,
2930 date : DateVO . now ( ) ,
3031 products : [ { productId : body . productId , quantity : body . quantity ?? 1 } ] ,
3132 } ) ,
3233 } ) ;
3334
34- const handler = ( body : IAddToCartValues ) => {
35- return mutateAsync ( body )
36- . then ( async ( ) => {
37- // optionally mutate related data
38- } )
39- . catch ( ( e ) => {
40- // listen for a specific error and act respectively (e.g. throwing a specific error and catch it later)
41-
42- // notify backend about the error if needed
43- Logger . error (
44- "An error occurred during adding an item to the cart" ,
45- e as Error
46- ) ;
47-
48- throw e ;
49- } ) ;
35+ const handler = async ( body : AddToCartPayload ) => {
36+ try {
37+ return await mutateAsync ( body ) ;
38+ } catch ( e ) {
39+ Logger . error (
40+ "An error occurred during adding an item to the cart" ,
41+ e as Error
42+ ) ;
43+
44+ if ( httpService . isError ( e ) && e . message === "Unknown product" ) {
45+ throw new UnknownProductError ( ) ;
46+ }
47+
48+ if ( httpService . isError ( e ) && e . message === "Product not available" ) {
49+ throw new ProductNotAvailableError ( ) ;
50+ }
51+
52+ throw new UnknownError ( ) ;
53+ }
5054 } ;
5155
5256 return [ handler , isPending ] as const ;
5357} ;
58+
59+ export class UnknownProductError extends Error {
60+ constructor ( ) {
61+ super ( "Unknown product" ) ;
62+ this . name = "UnknownProductError" ;
63+ }
64+ }
65+
66+ export class ProductNotAvailableError extends Error {
67+ constructor ( ) {
68+ super ( "Product not available" ) ;
69+ this . name = "ProductNotAvailableError" ;
70+ }
71+ }
0 commit comments