Error process

План

  • Як працюємо зараз
  • Які дані маємо
  • Обіцянки - цяцянки
  • Що робити?

Як працюємо зараз

export type UidRequest = {
  idMarketingUser?: number
  idReferredUser?: number
}

export type BadRequestResponse = {
  message: string
}

//--- можна розширити ---//

export type BadRequestResponse = {
  error: 'user_not_found'
         // на проді не розкриваємо деталей
         // це коли юзера з різних регіонів
       | 'not_access'
}

Які дані маємо

Обіцянки - цяцянки

interface Promise<T> {
  
  then<TResult1 = T, TResult2 = never>(
    onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
  ): Promise<TResult1 | TResult2>

  catch<TResult = never>(
    onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null
  ): Promise<T | TResult>

}
export interface Http {
  get<T>(url: string, data?: any): Promise<T>
  post<T>(
    url: string,
    data?: any,
    noGetData?: boolean,
  ): Promise<T>
}

Що з цього можна побудувати

PS. Не сильно багато

doSomething()  
  .then(doSomethingElseWithError)
  .catch(handleError)
  .then(doMoreStuff)
  .then(doMoreStuffWithError)
  .then(doFinalThing)
  .catch(handleAnotherError)

Пригадаємо проміси

f, err := os.Open("filename.ext")

if err != nil {
    log.Fatal(err)
}

// do something with the open *File f
async function apiGet<T1, T2 extends { error: string }>(
    url: string
): Promise<[T1, null] | [null, T2]> {
    try {
        return [
          await fetch(url).then(data => data.json()),
          null,
        ];
    } catch (e) {
        // @ts-ignore
        return [null, { error: e.message }];
    }
}
// --- types --- //
type MessagesResponse = {
    messages: { mess: string }[]
}

type MessagesErrorResponse = {
    error: 'user_not_found' | 'not_access'
}

type ErrGeneric<Good, Bad> = Promise<[Good, null] | [null, Bad]>

// --- api --- //
function getMessages(): ErrGeneric<MessagesResponse, MessagesErrorResponse> {
    return apiGet<MessagesResponse, MessagesErrorResponse>('chat/messages')
}

// --- code --- //
async function a() {
    const [data, err] = await getMessages()

    if (err !== null) {
        
    }

    if (data !== null) {
        console.log(data.messages)
    }
} 

Обробка помилок

export class BusinessError extends Error {
  name = 'BusinessError'
}

P.S. Наведений раніше приклад краще не використовувати link

Error

By Kolya Koval

Error

  • 233