토이 프로젝트_Velog 클론 코딩_2

추성결·2024년 6월 23일
0

이번에 로그인 기능을 구현하면서 에러 핸들링을 구현했는데, Nest.js와 다른 점이 있어 적어보려 한다.

Exception 구현

export class UnauthorizedException extends Error {
    status: number;

    constructor(message: string) {
        super(message);
        this.status = 401;
        this.name = 'UnauthorizedException';
        
    }
}

export class InternalServerException extends Error {
    status: number;

    constructor(message: string) {
        super(message);
        this.status = 500;
        this.name = 'InternalServerException';
    }
}
  • 이렇게 Error를 상속받은 각 에러 객체를 작성하고, 각 비즈니스 로직에서 throw 시킨다.
export const userLogin = async (userInfo: LoginInfo): Promise<LoginOutput> => {
    try {
        const user = await findUserByEmail(userInfo);
    
        if(user == null)
            throw new UnauthorizedException('User Not Found');

        const isMatch = await bcrypt.compare(userInfo.password, user.password);

        if(!isMatch)
            throw new UnauthorizedException('Password is not match');
        else {
            const payload: Payload = {
                id: user.userId,
                email: user.email,
            }

            const secret: string = process.env.JWT_SECRET as string
            const accessToken = jwt.sign(payload, secret, {expiresIn: '1h'});
            const refreshToken = jwt.sign(payload, secret, {expiresIn: '60d'});

            const result: LoginOutput = {
                accessToken: accessToken,
                refreshToken: refreshToken,
            }

            return result;
        }
    }
    catch(err) {
        console.log(err)
        throw new InternalServerException('internal server err');
    }
}

이 때, postman에서 일부러 틀린 password를 적은 후 요청을 보내면 app crush가 나면서 서버는 다른 요청을 받지 못하게 된다.

Nest.JS와 Node.JS와 다른점

  • Nest.JS에서는 내부적으러 전역 에러 핸들러를 제공한다고 한다. 그래서 애플리케이션에서 발생하는 보든 예외를 자동으로 잡아 처리한다. 하지만 Node.JS에서는 에러 핸들링 로직을 만들어야한다. 그래서 나는 메인 Server.ts에 핸들링하는 코드를 작성했다.
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
    console.error(err); // 에러 로깅
    if (err instanceof UnauthorizedException) {
        res.status(401).json({ message: err.message });
    } else if (err instanceof InternalServerException) {
        res.status(500).json({ message: err.message });
    } else {
        res.status(500).json({ message: "An unexpected error occurred" });
    }
});
  • err가 UnauthorizedException에서 상속받아 만들어진 객체인지 확인해서 message를 send시킨다.

오늘 작업

오늘 핸들링 작업 관련 수정하는게 시간이 오래 걸려서 아직 게시글 작성 로직을 만들지 못했다. 오늘 마무리하고, DB관련해서 다른 점이 있으면 포스트 할 것이다.

0개의 댓글