Нормально ли на практике писать такие классы express js
захотел как в nest js кастомные исключения написать , но не знаю делают так или нет на практике , есть ли смысл
import { Response } from "express";
enum TypeOfException {
ERROR = "error",
MESSAGE = "message"
}
export class Exception {
type: TypeOfException;
message: string;
code: number;
data?: any;
constructor(
code: number,
message: string,
type: TypeOfException,
data?: any
) {
this.type = type;
this.message = message;
this.code = code;
this.data = data;
}
exception(res: Response) {
return res
.status(this.code)
.json({ [this.type]: this.message, data: this.data });
}
}
export class BadRequestException extends Exception {
constructor(message: string) {
super(400, message, TypeOfException.ERROR);
}
}
export class UnauthorizedException extends Exception {
constructor(message: string) {
super(401, message, TypeOfException.ERROR);
}
}
export class CreatedSuccessfullyException extends Exception {
constructor(message: string, data?: any) {
super(201, message, TypeOfException.MESSAGE, data);
}
}
export class OkayException extends Exception {
constructor(message: string) {
super(200, message, TypeOfException.MESSAGE);
}
}
export class InternalServerException extends Exception {
constructor(message: string) {
super(500, message, TypeOfException.ERROR);
}
}
import { Request, Response, NextFunction } from "express";
import { Exception } from "../utils/Exceptions";
//middleware
export function errorHandler(
err: any,
req: Request,
res: Response,
next: NextFunction
) {
if (err instanceof Exception) {
return err.exception(res);
}
return res.status(500).json({ error: "Internal Server Error" });
}
import { NextFunction, Request, Response } from "express";
import { prisma } from "../../../prisma/prisma.client";
import bcrypt from "bcrypt";
import {
BadRequestException,
CreatedSuccessfullyException,
InternalServerException
} from "../../utils/Exceptions";
//controller
class UserController {
async register(req: Request, res: Response, next: NextFunction) {
const { email, password, name } = req.body;
if (!email || !password || !name) {
return next(new BadRequestException("Все поля обязательны"));
}
try {
const existUser = await prisma.user.findUnique({
where: {
email
}
});
if (existUser) {
return next(new BadRequestException("Пользователь уже существует"));
}
const hashedPassword = await bcrypt.hash(password, 5);
const user = await prisma.user.create({
data: {
email,
password: hashedPassword,
name
}
});
return next(
new CreatedSuccessfullyException("Пользователь успешно создан")
);
} catch (error: any) {
console.log(error);
return next(
new InternalServerException("Ошибка при создании пользователя")
);
}
}
async login(req: Request, res: Response, next: NextFunction) {
const { email, password } = req.body;
if (!email || !password) {
return next(new BadRequestException("Все поля обязательны"));
}
}
}
export default new UserController();