NotHtmlMimetype error handling

This commit is contained in:
DarkCat09 2023-09-21 13:18:12 +04:00
parent e6b61fb814
commit 1fc1d8e88b
No known key found for this signature in database
GPG Key ID: 0A26CD5B3345D6E3
4 changed files with 32 additions and 19 deletions

View File

@ -29,10 +29,6 @@ function apiErrorHandler(error: Error, reply: FastifyReply) {
});
}
if (error instanceof NotHtmlMimetypeError) {
return generateResponse(501);
}
if (getFastifyError(error)?.statusCode === 400) {
return generateResponse(400);
}
@ -45,10 +41,6 @@ function apiErrorHandler(error: Error, reply: FastifyReply) {
}
function htmlErrorHandler(error: Error, reply: FastifyReply, url: string) {
if (error instanceof NotHtmlMimetypeError) {
return reply.redirect(301, error.url);
}
if (getFastifyError(error)?.statusCode === 400) {
return reply.code(400).view("/templates/error.ejs", {
url,
@ -62,6 +54,7 @@ function htmlErrorHandler(error: Error, reply: FastifyReply, url: string) {
url,
code: error.code,
description: error.description,
proxyBtn: error instanceof NotHtmlMimetypeError,
});
}

View File

@ -3,7 +3,11 @@ export abstract class TxtDotError extends Error {
name: string;
description: string;
constructor(code: number, name: string, description: string) {
constructor(
code: number,
name: string,
description: string,
) {
super(description);
this.code = code;
this.name = name;
@ -13,22 +17,30 @@ export abstract class TxtDotError extends Error {
export class EngineParseError extends TxtDotError {
constructor(message: string) {
super(422, "EngineParseError", `Parse error: ${message}`);
super(
422,
"EngineParseError",
`Parse error: ${message}`,
);
}
}
export class LocalResourceError extends TxtDotError {
constructor() {
super(403, "LocalResourceError", "Proxying local resources is forbidden.");
super(
403,
"LocalResourceError",
"Proxying local resources is forbidden.",
);
}
}
export class NotHtmlMimetypeError extends Error {
name: string = "NotHtmlMimetypeError";
url: string;
constructor(url: string) {
super();
this.url = url;
export class NotHtmlMimetypeError extends TxtDotError {
constructor() {
super(
421,
"NotHtmlMimetypeError",
"Received non-HTML content, use proxy",
);
}
}

View File

@ -32,7 +32,7 @@ export default async function handlePage(
const mime: string | undefined = response.headers["content-type"]?.toString();
if (mime && mime.indexOf("text/html") === -1) {
throw new NotHtmlMimetypeError(url);
throw new NotHtmlMimetypeError();
}
return getFallbackEngine(urlObj.hostname, engine)(

View File

@ -15,6 +15,14 @@
<h1>txt<span class="dot-err">.</span></h1>
<p class="menu">
<a href="/" class="button">Home</a>
<% if (proxyBtn) { %>
<a
href="/proxy?url=<%= encodeURIComponent(url) %>"
class="button secondary"
>
Proxy
</a>
<% } %>
<a href="<%= url %>" class="button secondary">Original page</a>
</p>
<p><%= description %></p>