improve error handling

This commit is contained in:
Julian Krauser 2024-08-23 09:44:36 +02:00
parent e1ec65350d
commit bcfba8b448
5 changed files with 22 additions and 20 deletions

View file

@ -1,9 +1,7 @@
import { ExceptionBase } from "./exceptionsBaseType";
export default class BadRequestException extends Error implements ExceptionBase {
statusCode: number = 400;
import CustomRequestException from "./customRequestException";
export default class BadRequestException extends CustomRequestException {
constructor(msg: string) {
super(msg);
super(400, msg);
}
}

View file

@ -1,9 +1,7 @@
import { ExceptionBase } from "./exceptionsBaseType";
export default class InternalException extends Error implements ExceptionBase {
statusCode: number = 500;
import CustomRequestException from "./customRequestException";
export default class InternalException extends CustomRequestException {
constructor(msg: string) {
super(msg);
super(500, msg);
}
}

View file

@ -1,9 +1,7 @@
import { ExceptionBase } from "./exceptionsBaseType";
export default class UnauthorizedRequestException extends Error implements ExceptionBase {
statusCode: number = 401;
import CustomRequestException from "./customRequestException";
export default class UnauthorizedRequestException extends CustomRequestException {
constructor(msg: string) {
super(msg);
super(401, msg);
}
}

View file

@ -6,10 +6,10 @@ import InternalException from "../exceptions/internalException";
import { JWTHelper } from "../helpers/jwtHelper";
export default async function authenticate(req: Request, res: Response, next: Function) {
const bearer = req.headers.authorization;
const bearer = req.headers.authorization?.split(" ")?.[1] ?? undefined;
if (!bearer) {
throw new BadRequestException("Provide Authorization Header");
throw new BadRequestException("Provide valid Authorization Header");
}
let decoded: string | jwt.JwtPayload;

View file

@ -1,9 +1,17 @@
import { Request, Response } from "express";
import { ExceptionBase } from "../exceptions/exceptionsBaseType";
import CustomRequestException from "../exceptions/customRequestException";
export default function errorHandler(err: ExceptionBase, req: Request, res: Response, next: Function) {
let status = err.statusCode ?? 500;
let msg = err.message;
export default function errorHandler(err: ExceptionBase | Error, req: Request, res: Response, next: Function) {
let status = 500;
let msg = "Internal Server Error";
if (err instanceof CustomRequestException) {
status = err.statusCode;
msg = err.message;
}
console.log("Handler", err);
res.status(status).send(msg);
}