partey_workadventure/pusher/src/Controller/BaseController.ts

45 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-06-24 10:09:10 +02:00
import { HttpResponse } from "uWebSockets.js";
export class BaseController {
protected addCorsHeaders(res: HttpResponse): void {
2021-06-24 10:09:10 +02:00
res.writeHeader("access-control-allow-headers", "Origin, X-Requested-With, Content-Type, Accept");
res.writeHeader("access-control-allow-methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.writeHeader("access-control-allow-origin", "*");
}
/**
* Turns any exception into a HTTP response (and logs the error)
*/
2021-01-18 15:43:27 +01:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected errorToResponse(e: any, res: HttpResponse): void {
if (e && e.message) {
let url = e?.config?.url;
if (url !== undefined) {
2021-06-24 10:09:10 +02:00
url = " for URL: " + url;
} else {
2021-06-24 10:09:10 +02:00
url = "";
}
2021-06-24 10:09:10 +02:00
console.error("ERROR: " + e.message + url);
} else if (typeof e === "string") {
console.error(e);
}
if (e.stack) {
console.error(e.stack);
}
if (e.response) {
2021-06-24 10:09:10 +02:00
res.writeStatus(e.response.status + " " + e.response.statusText);
this.addCorsHeaders(res);
res.end(
"An error occurred: " +
e.response.status +
" " +
(e.response.data && e.response.data.message ? e.response.data.message : e.response.statusText)
);
} else {
2021-06-24 10:09:10 +02:00
res.writeStatus("500 Internal Server Error");
this.addCorsHeaders(res);
res.end("An error occurred");
}
}
}