codestates / codestates/conimals
[정새얀] 220601 Error - Handling
- Dominant language
- JavaScript
- Stars
- 3
- Forks
- 5
- PR merge metrics
- No merged PRs in 30d
Description
> 해결된 에러라면 라벨에 'Complete' 를 달아주세요.
> 미해결된 에러라면 라벨을 'In progress' 로 변경해주세요.
### 어떤 에러인가요?
- 사용자 정보를 가져오는 컨트롤러를 작성하고 포스트맨으로 요청을 보낼 시 데이터베이스에 해당 유저 정보가 있음에도 불구하고 404 상태코드와 함께 해당 사용자의 정보가 없다는 메시지를 띄움.
### 에러 메시지
```bash
GET /mypages/auth 404 56 - 11.272 ms
```
### 에러 핸들링 방법
- 계속해서 404가 나와서 아예 처음 썼던 코드를 전부 지우고 새로 코드를 작성한 후 포스트맨 요청을 넣었더니 200을 받을 수 있었다.
* 처음 작성했던 코드
```js
const { users, posts } = require('../../models');
module.exports = async (req, res) => {
const { id } = req.body;
const userInfo = await users.findOne({
attributes: ['id', 'userName', 'userEmail'],
where: { id },
});
// 해당 유저가 존재하지 않음
if (!userInfo) {
return res.status(404).json({ message: '회원 정보 조회에 실패했습니다' });
}
// 사용자가 업로드한 글
const { userId } = req.body;
const uploads = posts.findAll({
attributes: ['id', 'title', 'content', 'image'],
where: { userId },
order: [['createdAt']],
});
// 회원정보 응답
Promise.all([uploads]).then(([uploads]) => {
const { id, userName, userEmail } = userInfo;
return res.status(200).json({
data: {
id,
userName,
userEmail,
uploads,
},
message: '회원 정보 조회에 성공했습니다',
});
});
};
```
* 수정한 코드
```js
const { users, posts } = require('../../models');
const { isAuthorized } = require('../tokenFunctions');
module.exports = async (req, res) => {
const verify = isAuthorized(req);
if (!verify) {
return res.status(400).json({ message: '유효하지 않은 요청입니다' });
} else {
const userInfo = await users.findOne({
attributes: ['id', 'userName', 'userEmail', 'password'],
where: { id: verify.id },
});
const { userId } = req.body;
const uploads = posts.findAll({
attributes: ['id', 'title', 'content', 'image'],
where: { userId },
order: [['createdAt']],
});
if (!userInfo) {
return res.status(401).json({ message: '권한이 없습니다' });
} else {
const { id, userName, userEmail } = userInfo;
return res.status(200).json({
data: {
id,
userName,
userEmail,
uploads,
},
message: '회원 정보 조회에 성공하였습니다',
});
}
}
};
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.