Covenant

[Node.js] 에러처리 (Page Not Found)



Source. freepik.com


기본 코드


npm init

Node.js 애플리케이션을 초기화하고 package.json 파일을 생성합니다.


📂Root
|
├── 📂 node_modules   
├── 📂 controllers
|   └── 📄 errorControllers.js  <------ TODO!
|── 📂 public
|   └── 📄 404.html             <------ TODO!
├── 📄 index.js                 <------ TODO!
|   📄 package.json
|   📄 package-lock.json

작업할 디렉토리 구조는 위와 같습니다. 완성 코드 Github 에서 확인하세요.



const express = require('express');
const app = express();
const PORT = 5003;

app.get('/', (req, res) => 
    res.send("Hello World!")
)

app.listen(PORT, () => {
    console.log(`Server is running on port: ${PORT}`);
})
index.js 기본 코드

index.js 기본 코드는 위와 같습니다. 5003번 포트를 이용할 것이며 웹의 root에서는 Hello World를 보여줄 것입니다.


nodemon index.js
node index.js

nodemon 혹은 node 명령어로 서버를 실행합니다.



http://localhost:5003/을 통해 접속하면 Hello World가 정상적으로 보입니다.



http://localhost:5003/123과 같이 다른 PATH로 접속한다고 하면 위와 같은 오류 메세지를 만날 수 있습니다. 이럴 경우에 Page Not Found 에러처리를 할 것입니다.



에러 처리 코드 작성


HTTP는 다양한 상태코드를 가지고 있습니다. 상태 코드를 모른다면? Wiki 상태코드 상태코드를 숫자를 직접 넣어도 되겠지만 코드의 가독성을 위하여 새로운 패키지를 설치할 것입니다.


npm install http-status-codes --save

Node.js 패키지의 루트에 controllers 디렉토리를 생성한 다음 errorControllers.js를 아래와 같이 작성합니다.


const httpStatus = require('http-status-codes');

exports.pageNotFoundError = (req, res) => {
    let errorCode = httpStatus.NOT_FOUND;
    res.status(errorCode);
    res.send(`${errorCode} | The page does not exist! `);
}

exports.respondInternalError = (errors, req, res, next) => {
    let errorCode = httpStatus.INTERNAL_SERVER_ERROR;
    console.log(`Error occured: ${errors.stack}`)
    res.status(errorCode);
    res.send(`${errorCode} | Sorry, our application is experiencing a problem!`);
};
controllers 디렉토리의 errorControllers.js

404 에러는 pageNotFoundError가 처리합니다. 500 에러는 respondInternalError가 처리합니다.


const express = require('express');
const app = express();
const PORT = 5003;
const errorController = require("./controllers/errorControllers");

app.get('/', (req, res) => 
    res.send("Hello World!")
)

app.use(errorController.pageNotFoundError);
app.use(errorController.respondInternalError);


app.listen(PORT, () => {
    console.log(`Server is running on port: ${PORT}`);
})
index.js 수정

app.use(errorController.pageNotFoundError);app.use(errorController.respondInternalError); 미들웨어를 index.js에 추가해줍니다.



http://localhost:5003/123을 입력하면 Page Not Found를 확인할 수 있습니다. 500 에러 처리도 만들었기 때문에 500 에러가 난다면 이에 대한 처리가 보여질 것입니다.



404.html을 만들어보자


위에서 간단하게 send를 이용하여 404 처리를 하였습니다. 404를 위한 템플릿을 만들어보겠습니다.

exports.pageNotFoundError = (req, res) => {
    let errorCode = httpStatus.NOT_FOUND;
    res.status(errorCode);
    res.sendFile(`./public/${errorCode}.html`,{
        root: "./"
    });
};

errorControllers.js의 pageNotFoundError를 위와 같이 수정합니다. res.sendFile은 에러 페이지의 경로를 특정하는데 사용합니다.

<h1>404</h1>
404.html


http://localhost:5003/123로 접속시 404.html을 볼 수 있습니다.


public 디렉토리에 404.html을 위와 같이 간단하게 만듭니다. 프로그래머스 404 머쓱 이벤트 를 진행한 적이 있으며 구글 검색시 다양한 404 템플릿이 나옵니다. 여러분들의 404를 재치있게 잘 만들어보세요~