forked from earthkingman/42Swim
-
Notifications
You must be signed in to change notification settings - Fork 1
Error Class
๋ฐ์ง์จ edited this page Oct 16, 2021
·
2 revisions
์์ฑ์ | ์์ฑ์ผ์ |
---|---|
earthkingman | 2021-10-16 |
์๋ฌ ํด๋์ค๋ฅผ ์์ฑํด์ ์ฝ๋ ์ค๋ณต์ ์ต์ํ
- Error Class ์์ฑ
class HttpException extends Error {
status: number;
message: string;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
}
}
export default HttpException;
- Error ์ค๋ฅ ์ฒ๋ฆฌ ๋ฏธ๋ค์จ์ด
import { NextFunction, Request, Response } from 'express';
import HttpException from '../exceptions/HttpException';
function errorMiddleware(error: HttpException, request: Request, response: Response, next: NextFunction) {
const status = error.status || 500;
const message = error.message || 'Something went wrong';
response
.status(status)
.send({
status,
message,
})
}
export default errorMiddleware;
- index.ts
errorMiddleware๋ฅผ ๊ฐ์ฅ ํ๋จ์ ๋๋๋ ์ด์ Express๋ ๋ชจ๋ ๋ฏธ๋ค์จ์ด ํจ์ ๋ฐ ๋ผ์ฐํธ๋ฅผ ์คํํ์ผ๋ฉฐ ์ด๋ค ์ค ์ด๋ ๊ฒ๋ ์๋ตํ์ง ์์๋ค๋ ๊ฒ์ ๋ํ๋ด๊ธฐ ๋๋ฌธ
~~
app.use(cors(corsOptions));
app.use("/auth", authRouter);
app.use("/posts", postRouter);
app.use("/users", userRouter);
app.use("/pages", pageRouter);
app.use(errorMiddleware);
~~
- Contoller (์์์ฝ๋)
next() ํจ์๋ก ์ด๋ ํ ๋ด์ฉ์ ์ ๋ฌํ๋ ๊ฒฝ์ฐ('route'๋ผ๋ ๋ฌธ์์ด ์ ์ธ), Express๋ ํ์ฌ์ ์์ฒญ์ ์ค๋ฅ๊ฐ ์๋ ๊ฒ์ผ๋ก ๊ฐ์ฃผํ๋ฉฐ, ์ค๋ฅ ์ฒ๋ฆฌ์ ๊ด๋ จ๋์ง ์์ ๋๋จธ์ง ๋ผ์ฐํ ๋ฐ ๋ฏธ๋ค์จ์ด ํจ์๋ฅผ ๊ฑด๋๋๋๋ค.
const createAnswerLike = async (req: DecodedRequest, res: Response, next: NextFunction) => {
const { answerId, isLike, answerUserId } = req.body;
const userId: number = req.decodedId;
const likeService: LikeService = new LikeService();
try {
await likeService.createAnswerLike({ userId, answerId, isLike, answerUserId });
return res.status(200).json({
result: true,
message: "create Success",
})
} catch (error) {
console.log(error);
next(new HttpException(404, 'Answer not found'));
}
}