이번에 로그인 기능을 구현하면서 에러 핸들링을 구현했는데, Nest.js와 다른 점이 있어 적어보려 한다.
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';
}
}
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가 나면서 서버는 다른 요청을 받지 못하게 된다.
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" });
}
});
오늘 핸들링 작업 관련 수정하는게 시간이 오래 걸려서 아직 게시글 작성 로직을 만들지 못했다. 오늘 마무리하고, DB관련해서 다른 점이 있으면 포스트 할 것이다.