mirror of
https://gitlab.com/comunic/comunicapiv2
synced 2024-12-27 22:18:52 +00:00
Handle errors
This commit is contained in:
parent
293752b0f4
commit
1ddf156cc4
@ -16,7 +16,7 @@ export enum RouteType {
|
||||
export interface Route {
|
||||
type ?: RouteType,
|
||||
path: string,
|
||||
cb: (req : RequestHandler) => void,
|
||||
cb: (req : RequestHandler) => Promise<void> | void,
|
||||
}
|
||||
|
||||
export const Routes : Route[] = [
|
||||
|
@ -12,6 +12,8 @@ import { checkMail } from "../utils/StringUtils";
|
||||
export class RequestHandler {
|
||||
|
||||
private client : APIClient = null;
|
||||
|
||||
private responseSent = false;
|
||||
|
||||
public constructor(private req : Request, private response : Response) {}
|
||||
|
||||
@ -113,6 +115,10 @@ export class RequestHandler {
|
||||
* @param message The message to send
|
||||
*/
|
||||
public error(code : number, message : string) {
|
||||
|
||||
if(this.responseSent)
|
||||
return;
|
||||
|
||||
this.response.status(code).send({
|
||||
error: {
|
||||
code: code,
|
||||
@ -120,6 +126,8 @@ export class RequestHandler {
|
||||
}
|
||||
});
|
||||
|
||||
this.responseSent = true;
|
||||
|
||||
throw Error("Could not complete request!");
|
||||
}
|
||||
|
||||
@ -129,6 +137,9 @@ export class RequestHandler {
|
||||
* @param message Message associated to success
|
||||
*/
|
||||
public success(message: string) {
|
||||
|
||||
this.responseSent = true;
|
||||
|
||||
this.response.send({
|
||||
success: message
|
||||
});
|
||||
@ -140,6 +151,9 @@ export class RequestHandler {
|
||||
* @param data The data to send back to the server
|
||||
*/
|
||||
public send(data: any) {
|
||||
|
||||
this.responseSent = true;
|
||||
|
||||
this.response.send(data);
|
||||
}
|
||||
}
|
14
src/main.ts
14
src/main.ts
@ -32,11 +32,19 @@ async function init() {
|
||||
const cb = async (req : express.Request, res : express.Response)=> {
|
||||
const handler = new RequestHandler(req, res);
|
||||
|
||||
// Check API tokens
|
||||
await handler.checkAPITokens();
|
||||
try {
|
||||
|
||||
// Check API tokens
|
||||
await handler.checkAPITokens();
|
||||
|
||||
route.cb(handler);
|
||||
const cb = route.cb(handler);
|
||||
if(cb)
|
||||
await cb;
|
||||
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
handler.error(500, "Internal error.");
|
||||
}
|
||||
};
|
||||
|
||||
if(route.type == RouteType.GET)
|
||||
|
Loading…
Reference in New Issue
Block a user