2023-08-16 13:20:24 +03:00
|
|
|
import { FastifyReply, FastifyRequest } from "fastify";
|
2023-08-21 17:35:25 +03:00
|
|
|
import { NotHtmlMimetypeError, TxtDotError } from "./main";
|
|
|
|
import { getFastifyError } from "./validation";
|
2023-08-16 13:20:24 +03:00
|
|
|
|
|
|
|
export default function errorHandler(
|
|
|
|
error: Error,
|
|
|
|
_: FastifyRequest,
|
|
|
|
reply: FastifyReply
|
|
|
|
) {
|
2023-08-21 17:35:25 +03:00
|
|
|
// TODO: check if req.url starts with "/api/" and return JSON
|
|
|
|
|
|
|
|
return htmlErrorHandler(error, reply);
|
|
|
|
}
|
|
|
|
|
|
|
|
function htmlErrorHandler(error: Error, reply: FastifyReply) {
|
2023-08-16 13:20:24 +03:00
|
|
|
if (error instanceof NotHtmlMimetypeError) {
|
|
|
|
return reply.redirect(301, error.url);
|
2023-08-21 17:35:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (getFastifyError(error)?.statusCode === 400) {
|
2023-08-21 16:03:28 +03:00
|
|
|
return reply.code(400).view("/templates/error.ejs", {
|
2023-08-21 17:35:25 +03:00
|
|
|
code: 400,
|
|
|
|
description: `Invalid parameter specified: ${error.message}`,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if (error instanceof TxtDotError) {
|
|
|
|
return reply.code(error.code).view("/templates/error.ejs", {
|
|
|
|
code: error.code,
|
|
|
|
description: error.description,
|
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", {
|
|
|
|
code: 500,
|
|
|
|
description: `${error.name}: ${error.message}`,
|
|
|
|
});
|
2023-08-16 13:20:24 +03:00
|
|
|
}
|