Моя проблема следующая:
//express server
app.post('/register', (req, res) => {
const {
password,
passwordConfirm
} = req.body;
if (password === passwordConfirm) {
//...
} else {
res.status(400).json("Passwords aren't matching")
}
})
//react function
onSubmitSignIn = () => {
const { password, passwordConfirm } = this.state;
let data = new FormData();
data.append('password', password);
data.append('passwordConfirm', passwordConfirm);
fetch('http://localhost:3001/register', {
method: 'post',
body: data
})
.then(response => response.json())
.then(user => {
//logs error message here
console.info(user)
})
//but I want to catch it here, and set the message to the state
.catch(alert => this.setState({alert}))
}
Когда я отправляю код состояния и сообщение от express в качестве ответа, интерфейс, очевидно, распознает его как ответ, поэтому он записывает сообщение в консоль как «пользователь». Но как отправить ошибку, которая попадает в функцию перехвата?
Что делать, если выдает ошибку:
app.get("/", function (req, res) {
throw new Error("BROKEN"); // Express will catch this on its own.
});
А потом отловить эту ошибку в интерфейсе?
См. здесь для справки.
РЕДАКТИРОВАТЬ
Может, стоит вернуть ошибку с return next()
, чтобы остальной код не обрабатывался серверным методом:
app.get("/", function (req, res) {
return next(new Error('BROKEN'));
});
fetch
действительно выдаст ошибку только в том случае, если по какой-то причине не может вызвать API. Другими словами, это будет ошибка при сетевых ошибках. Это не будет явной ошибкой для кодов состояния, отличных от 2XX
.
Вам необходимо проверить свойство ok
, как описано здесь:
-
fetch('http://localhost:3001/register', {
method: 'post',
body: data
})
.then(response => {
if (!response.ok) {
throw new Error('my api returned an error')
}
return response.json()
})
.then(user => {
console.info(user)
})
.catch(alert => this.setState({alert}))
Проблема в том, что fetch
не распознает ошибки HTTP как отклонения обещаний.
The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.
(Источник)
Вы можете проверить связанный источник репозитория fetch
, в котором также содержится предложение по обработке статусов ошибок HTTP.
//express server
app.post('/register', (req, res) => {
try {
const {
password,
passwordConfirm
} = req.body;
if (password === passwordConfirm) {
//...
} else {
res.status(400).json("Passwords aren't matching")
}
} catch (error) {
res.status(500).send(error);
}
})
//react function
onSubmitSignIn = () => {
const {
password,
passwordConfirm
} = this.state;
let data = new FormData();
data.append('password', password);
data.append('passwordConfirm', passwordConfirm);
fetch('http://localhost:3001/register', {
method: 'post',
body: data
})
.then(response => response.json())
.then(user => {
//logs error message here
console.info(user)
})
//but I want to catch it here, and set the message to the state
.catch(alert => this.setState({
alert
}))
}
добавьте блок try catch @ уровень контроллера для управления ошибкой на стороне интерфейса