백엔드
[백엔드] next(Error)란?
ehddkDEV
2025. 1. 7. 11:24
백엔드를 하다보면 예외처리를 필수로 해줘야 한다.
주로 try & catch문으로 성공과 실패 처리 로직을 작성해준다.
next.js와 node.js를 이용해서 백엔드를 구현했을때를 살펴보자.
next(Error)란?
-> Express의 에러 처리 미들웨어로 에러를 전달하는 방식
주로 컨트롤러 레이어에서 사용한다.
예를 들어 인증 api를 구현할때
/api/auth/controller/auth.controller.ts
async login(req: Request, res: Response, next: NextFunction) {
try {
const { loginId, password } = req.body;
const result = await this._authService.login(loginId, password);
res.status(200).json({
message: "로그인 성공",
data: result,
});
} catch (error) {
res.status(500).json({ message: "로그인 실패" });
next(error);
}
}
catch문에서 next(error)를 함으로써 에러 처리 미들웨어에 전달하는 것이다.
처음에 난 서비스 레이어에서도 썼었는데, 서비스에서는 throw로 해당 에러 응답을 컨트롤러로 전달만 해주는 것이 옳다고 한다!
async login(id: string, password: string): Promise<string> {
const findUser = await this._userRepository.findById(id);
if (!findUser) {
console.log("존재 하지 않는 회원입니다.");
throw new HttpException(404, "존재 하지 않는 회원입니다");
}
`````
}