Skip to content

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'));
	}
}