import app from '@adonisjs/core/services/app' import { type HttpContext, ExceptionHandler } from '@adonisjs/core/http' import { isDockerUnreachable } from '#services/docker_service' export default class HttpExceptionHandler extends ExceptionHandler { /** * In debug mode, the exception handler will display verbose errors * with pretty printed stack traces. */ protected debug = !app.inProduction /** * The method is used for handling errors and returning * response to the client */ async handle(error: unknown, ctx: HttpContext) { /** * Shield redirects back on a bad CSRF token, which means nothing for * the API: answer with a JSON error instead. */ if ((error as { code?: string })?.code === 'E_BAD_CSRF_TOKEN') { return ctx.response.forbidden({ message: 'Session expirée ou jeton de sécurité invalide : recharge la page.', }) } if (isDockerUnreachable(error)) { return ctx.response.serviceUnavailable({ message: 'Docker est injoignable : le socket Docker est-il monté dans le conteneur ?', }) } /** * Errors of the Docker API (unknown container, conflict…). */ const dockerError = error as { statusCode?: number; json?: { message?: string } } if (typeof dockerError?.statusCode === 'number' && dockerError.json?.message) { return ctx.response .status(dockerError.statusCode === 404 ? 404 : 400) .send({ message: `Docker : ${dockerError.json.message}` }) } return super.handle(error, ctx) } /** * The method is used to report error to the logging service or * the a third party error monitoring service. * * @note You should not attempt to send a response from this method. */ async report(error: unknown, ctx: HttpContext) { return super.report(error, ctx) } }