txtdot/packages/server/src/errors/handler.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

import { FastifyReply, FastifyRequest } from 'fastify';
import { NotHtmlMimetypeError } from './main';
import { getFastifyError } from './validation';
2023-08-16 13:20:24 +03:00
2024-05-13 12:54:14 +03:00
import { TxtDotError } from '@txtdot/sdk';
import { IGetSchema } from '../types/requests/browser';
import config from '../config';
2023-09-20 13:40:57 +03:00
2023-08-16 13:20:24 +03:00
export default function errorHandler(
error: Error,
req: FastifyRequest,
2023-08-16 13:20:24 +03:00
reply: FastifyReply
) {
if (req.originalUrl.startsWith('/api/')) {
return apiErrorHandler(error, reply);
}
2023-09-20 13:40:57 +03:00
const url = (req as FastifyRequest<IGetSchema>).query.url;
return htmlErrorHandler(error, reply, url);
2023-08-21 17:35:25 +03:00
}
function apiErrorHandler(error: Error, reply: FastifyReply) {
function generateResponse(code: number) {
return reply.code(code).send({
data: null,
error: {
code: code,
name: error.name,
message: error.message,
},
});
}
if (getFastifyError(error)?.statusCode === 400) {
return generateResponse(400);
}
if (error instanceof TxtDotError) {
return generateResponse(error.code);
}
return generateResponse(500);
}
2023-09-20 13:40:57 +03:00
function htmlErrorHandler(error: Error, reply: FastifyReply, url: string) {
2023-08-21 17:35:25 +03:00
if (getFastifyError(error)?.statusCode === 400) {
return reply.code(400).view('/templates/error.ejs', {
2023-09-20 13:40:57 +03:00
url,
2023-08-21 17:35:25 +03:00
code: 400,
description: `Invalid parameter specified: ${error.message}`,
});
2023-08-21 17:35:25 +03:00
}
if (error instanceof TxtDotError) {
return reply.code(error.code).view('/templates/error.ejs', {
2023-09-20 13:40:57 +03:00
url,
2023-08-21 17:35:25 +03:00
code: error.code,
description: error.description,
2024-03-07 14:49:54 +03:00
proxyBtn:
error instanceof NotHtmlMimetypeError && config.env.proxy.enabled,
2023-08-21 16:03:28 +03:00
});
2023-08-16 13:20:24 +03:00
}
2023-08-21 17:35:25 +03:00
return reply.code(500).view('/templates/error.ejs', {
2023-09-20 13:40:57 +03:00
url,
2023-08-21 17:35:25 +03:00
code: 500,
description: `${error.name}: ${error.message}`,
});
2023-08-16 13:20:24 +03:00
}