http-errors

Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Следующая версия
Предыдущая версия
http-errors [2024/06/01 15:10]
tro создано
http-errors [2024/06/03 19:02] (текущий)
tro
Строка 4: Строка 4:
 npm install http-errors npm install http-errors
 </code> </code>
 +Створюємо мідлвеар що буде займатись обробкою помилок. Один мідлвеар для обробок помилок, другий для обробки відсутності запрашуємо роутінга
 <code> <code>
- // src/controllers/students.js +import { isHttpError } from 'http-errors';
  
-// 1. Імпортуємо функцію з бібліотеки +//Функція обробки помилок errorHandlerMiddleware.js 
-import createHttpError from 'http-errors';+export const errorHandlerMiddleware = (error, req, res, next) => {
  
-/* Інший код файлу */+    if (isHttpError(error)) { 
 +      res.status(error.status).json({ 
 +      status: error.status, 
 +      message: error.message, 
 +      data: {"message": error.message}, 
 +      }); 
 +    } else { 
 +      res.status(500).json({ 
 +      status: 500, 
 +      message: error.message, 
 +      }); 
 +    } 
 +  }; 
 + 
 +</code> 
 +<code> 
 +// notFoundHendker.js 
 +//Функція обробки помилок у разі відсутності маршруту 
 +export const notFoundHandler = (req, res) => { 
 +    res.status(404).send('Oops! Route was not found!'); 
 +  }; 
 +</code> 
 +Підключаємо ці мідлвеари для обробки помилок у головний файл server.js 
 +<code> 
 +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}`); 
 +    }); 
 +     
 +
 +</code> 
 +В модулі де необхідно обробити помилку, підключаємо бібліотеку і описуемо помилку 
 +<code> 
 +import createHttpError from 'http-errors';
  
-export const getStudentByIdController = async (req, res, next) => { +export const getContactsById = async (id) => { 
-  const { studentId = req.params; +    const idobj = _id: id };
-  const student = await getStudentById(studentId);+
  
-  if (!student) { +    if (!mongoose.Types.ObjectId.isValid(id)) { 
-    // 2. Створюємо та налаштовуємо помилку +        throw createHttpError(404, 'invalid ID'); 
-    next(createHttpError(404, 'Student not found')); +      }
-    return+
-  }+
  
-  res.json(+      const contactsfound = await ContactCollection.find(idobj);
-    status: 200, +
-    message: `Successfully found student with id ${studentId}!`, +
-    data: student, +
-  })+
-};+
  
 +      if (!contactsfound || contactsfound.length === 0) {
 +        throw createHttpError(404, `Contact with id ${id} not found!`);
 +    }
 +    return contactsfound;
 +}
 </code> </code>
 +Тепер при створенні помилки чере **throw createHttpError(404, `Contact with id ${id} not found!`);**  бібліотека автоматично перехватить помилку і передасть в обробку у мідлваре **errorHandlerMiddleware.js** або **notFoundHandler.js**
  • /sites/data/attic/http-errors.1717254657.txt.gz
  • Последнее изменение: 2024/06/01 15:10
  • tro