From e7057e4b0c316961c66d96778aa9cc30407dad4d Mon Sep 17 00:00:00 2001 From: krutoo Date: Thu, 21 Mar 2024 11:52:52 +0500 Subject: [PATCH] #38 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - preset: унифицирована обработка ошибки внутри обработчиков (bun/node) (patch) - добавлена утилита formatHandlerError (patch) --- .../bun-handler/providers/handler-main.tsx | 35 +++++---------- .../node-handler/providers/handler-main.tsx | 43 ++++++------------- src/preset/node/utils/handler-provider.ts | 2 +- .../server/utils/format-handler-error.ts | 38 ++++++++++++++++ src/tokens.ts | 2 +- 5 files changed, 64 insertions(+), 56 deletions(-) create mode 100644 src/preset/server/utils/format-handler-error.ts diff --git a/src/preset/bun-handler/providers/handler-main.tsx b/src/preset/bun-handler/providers/handler-main.tsx index 0e275f3..477b87f 100644 --- a/src/preset/bun-handler/providers/handler-main.tsx +++ b/src/preset/bun-handler/providers/handler-main.tsx @@ -1,9 +1,9 @@ /* eslint-disable require-jsdoc, jsdoc/require-jsdoc */ import { Resolve } from '../../../di'; import { KnownToken } from '../../../tokens'; -import { ResponseError, applyMiddleware } from '../../../http'; +import { applyMiddleware } from '../../../http'; import { HelmetContext } from '../../server/utils/regular-helmet'; -import { LogLevel } from '../../../log'; +import { formatHandlerError } from '../../server/utils/format-handler-error'; export function provideHandlerMain(resolve: Resolve) { const config = resolve(KnownToken.Config.base); @@ -39,37 +39,22 @@ export function provideHandlerMain(resolve: Resolve) { return new Response(body, { headers }); } catch (error) { - let logLevel: LogLevel | null = 'error'; - let message: string; - let statusCode = 500; // по умолчанию, если на этапе подготовки страницы что-то не так, отдаем 500 - let redirectLocation: string | null = null; + const { response, log } = formatHandlerError(error); - if (error instanceof Error) { - message = error.message; - - if (error instanceof ResponseError) { - statusCode = error.statusCode; - redirectLocation = error.redirectLocation; - logLevel = error.logLevel; - } - } else { - message = String(error); - } - - if (logLevel && logger[logLevel]) { - logger[logLevel](error); + if (log.level && logger[log.level]) { + logger[log.level](error); } - if (statusCode > 299 && statusCode < 400 && redirectLocation) { + if (response.status > 299 && response.status < 400 && response.redirectLocation) { return new Response(null, { - status: statusCode, + status: response.status, headers: { - Location: redirectLocation, + Location: response.redirectLocation, }, }); } else { - return new Response(message, { - status: statusCode, + return new Response(response.body, { + status: response.status, }); } } diff --git a/src/preset/node-handler/providers/handler-main.tsx b/src/preset/node-handler/providers/handler-main.tsx index a7bb80f..eea000f 100644 --- a/src/preset/node-handler/providers/handler-main.tsx +++ b/src/preset/node-handler/providers/handler-main.tsx @@ -1,15 +1,15 @@ import type { Resolve } from '../../../di'; +import type express from 'express'; import { KnownToken } from '../../../tokens'; import { HelmetContext } from '../../server/utils/regular-helmet'; -import { ResponseError } from '../../../http'; -import { LogLevel } from '../../../log'; +import { formatHandlerError } from '../../server/utils/format-handler-error'; /** * Провайдер главной функции обработчика входящего http-запроса. * @param resolve Функция для получения зависимости по токену. * @return Главная функция. */ -export function provideHandlerMain(resolve: Resolve): VoidFunction { +export function provideHandlerMain(resolve: Resolve): express.Handler { const config = resolve(KnownToken.Config.base); const logger = resolve(KnownToken.logger); const context = resolve(KnownToken.ExpressHandler.context); @@ -18,7 +18,7 @@ export function provideHandlerMain(resolve: Resolve): VoidFunction { const extras = resolve(KnownToken.Http.Handler.Response.specificExtras); const Helmet = resolve(KnownToken.Http.Handler.Page.helmet); const abortController = resolve(KnownToken.Http.Fetch.abortController); - const format = resolve(KnownToken.Http.Handler.Page.formatResponse); + const formatResponse = resolve(KnownToken.Http.Handler.Page.formatResponse); const getAssets = typeof assetsInit === 'function' ? assetsInit : () => assetsInit; @@ -37,42 +37,27 @@ export function provideHandlerMain(resolve: Resolve): VoidFunction { const assets = await getAssets(); const meta = extras.getMeta(); - const { body, headers } = await format( + const jsx = ( {await render()} - , - assets, - meta, + ); + const { body, headers } = await formatResponse(jsx, assets, meta); + headers.forEach((hValue, hName) => context.res.setHeader(hName, hValue)); context.res.send(body); } catch (error) { - let logLevel: LogLevel | null = 'error'; - let message: string; - let statusCode = 500; // по умолчанию, если на этапе подготовки страницы что-то не так, отдаем 500 - let redirectLocation: string | null = null; - - if (error instanceof Error) { - message = error.message; - - if (error instanceof ResponseError) { - statusCode = error.statusCode; - redirectLocation = error.redirectLocation; - logLevel = error.logLevel; - } - } else { - message = String(error); - } + const { response, log } = formatHandlerError(error); - if (statusCode > 299 && statusCode < 400 && redirectLocation) { - context.res.redirect(statusCode, redirectLocation); + if (response.status > 299 && response.status < 400 && response.redirectLocation) { + context.res.redirect(response.status, response.redirectLocation); } else { - context.res.status(statusCode).send(message); + context.res.status(response.status).send(response.body); } - if (logLevel && logger[logLevel]) { - logger[logLevel](error); + if (log.level && logger[log.level]) { + logger[log.level](error); } } diff --git a/src/preset/node/utils/handler-provider.ts b/src/preset/node/utils/handler-provider.ts index d4b5ab1..125a1dd 100644 --- a/src/preset/node/utils/handler-provider.ts +++ b/src/preset/node/utils/handler-provider.ts @@ -16,7 +16,7 @@ export function HandlerProvider(getApp: () => Application): Provider void>('express-handler/main'), + main: createToken('express-handler/main'), /** Токен "контекста" обработчика. Контекст содержит все аргументы, доступные обработчику (req, res, next). */ context: createToken('express-handler/context'),