import { Context } from '../context'; import { MiddlewareProvider } from '../middleware'; import { ErrorHandlerProvider } from '../error/error-handler-provider'; import { Dispatcher } from './dispatcher-protocol'; import { Component, Autowired, Logger } from '@celljs/core'; import { HandlerExecutionChain, HandlerMapping } from '../handler/handler-protocol'; import { STATUS_CODES } from 'node:http'; import { HttpStatus } from '@celljs/http'; import { HttpError } from '../error/http-error'; import { ErrorResponseUtil } from '../error/error-response-util'; @Component(Dispatcher) export class DispatcherImpl implements Dispatcher { @Autowired(HandlerExecutionChain) protected handlerExecutionChain: HandlerExecutionChain; @Autowired(HandlerMapping) protected readonly handlerMapping: HandlerMapping; @Autowired(MiddlewareProvider) protected middlewareProvider: MiddlewareProvider; @Autowired(ErrorHandlerProvider) protected errorHandlerProvider: ErrorHandlerProvider; @Autowired(Logger) protected readonly logger: Logger; async dispatch(ctx: Context): Promise { try { Context.setCurrent(ctx); const middlewares = this.middlewareProvider.provide(); await this.handlerExecutionChain.execute(middlewares, () => this.handlerMapping.handle()); } catch (err) { try { await this.handleError(ctx, err); } finally { // After the handlers: the status they answered tells a refused request from a failure. this.logError(err, ctx.response.statusCode); } } } /** * Server errors with their stack at the error level. Client errors are answers, not failures, and only * go to the debug level: a 4xx `HttpError` (a 404 for an unknown path), or any error a handler answered * with a redirect or a 4xx (login required, access denied). */ protected logError(err: unknown, status?: number): void { const answered = status !== undefined && status >= 300 && status < 500; if ((err instanceof HttpError && err.statusCode < 500) || answered) { if (this.logger.isEnabled('debug')) { this.logger.debug(`${err instanceof HttpError ? err.statusCode : status} ${err instanceof Error ? err.message : String(err)}`); } return; } // The logger writes an error with its stack and causes. this.logger.error(err instanceof Error ? err : String(err)); } /** * The handler with the highest priority that can handle the error answers; when its `handle` throws, * the next one is tried. When none answers, the response ends with a bare 500, so no request hangs. */ protected async handleError(ctx: Context, err: Error): Promise { const errorHandlers = this.errorHandlerProvider.provide(); for (const handler of errorHandlers) { if (await handler.canHandle(ctx, err)) { try { await handler.handle(ctx, err); } catch (error) { // A handler that gives the error back (it cannot answer it) is not a second failure. if (error !== err) { this.logError(error); } continue; } return; } } ErrorResponseUtil.end(ctx, HttpStatus.INTERNAL_SERVER_ERROR, STATUS_CODES[HttpStatus.INTERNAL_SERVER_ERROR]!); } }