Это старая версия документа!
http-errors
Для зручного створення помилок скористаємось пакетом http-errors. Інсталюємо його командою:
npm install http-errors
Створюємо мідлвеар що буде займатись обробкою помилок. Один мідлвеар для обробок помилок, другий для обробки відсутності запрашуємо роутінга
// src/controllers/students.js
// 1. Імпортуємо функцію з бібліотеки
import createHttpError from 'http-errors';
/* Інший код файлу */
export const getStudentByIdController = async (req, res, next) => {
const { studentId } = req.params;
const student = await getStudentById(studentId);
if (!student) {
// 2. Створюємо та налаштовуємо помилку
next(createHttpError(404, 'Student not found'));
return;
}
res.json({
status: 200,
message: `Successfully found student with id ${studentId}!`,
data: student,
});
};
// notFoundHendker.js
//Функція обробки помилок у разі відсутності маршруту
export const notFoundHandler = (req, res) => {
res.status(404).send('Oops! Route was not found!');
};
Підключаємо ці мідлвеари для обробки помилок у головний файл server.js
import express from 'express';
import pino from 'pino-http';
import cors from 'cors';
import { env } from './utils/env.js';
import { ENV_VARS } from './const/const.js';
import contactsRouter from './routers/contacts.js';
import { errorHandlerMiddleware } from './middlewares/errorHandler.js';
import { notFoundHandler } from './middlewares/notFoundHandler.js';
//Запуск сервера
export const setupServer=()=> {
//Ініціалізація сервера
const app = express();
// app.use(pino());
// app.use(
// pino({
// transport: {
// target: 'pino-pretty',
// },
// }),
// );
app.use(cors());
//Додавання middleware для парсингу JSON
app.use(
express.json({
limit: '1mb',
type: ['application/json', 'application/vnd.api+json'],
}),
);
//Підключення маршрутів
app.use(contactsRouter);
//підключення обробників помилок
app.use(errorHandlerMiddleware);
app.use(notFoundHandler);
//Запуск сервера
const PORT = env(ENV_VARS.PORT, 3000);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
}
В модулі де необхідно обробити помилку, підключаємо бібліотеку і описуемо помилку
import createHttpError from 'http-errors';
export const getContactsById = async (id) => {
const idobj = { _id: id };
if (!mongoose.Types.ObjectId.isValid(id)) {
throw createHttpError(404, 'invalid ID');
}
const contactsfound = await ContactCollection.find(idobj);
if (!contactsfound || contactsfound.length === 0) {
throw createHttpError(404, `Contact with id ${id} not found!`);
}
return contactsfound;
}