werfen Ist es möglich, einen Fehler in den .then() Block in Axios absichtlich zu werfen? Zum Beispiel, wenn die API mit 204 Statuscode antwortet, könnte ich einen Fehler werfen und den catch-Block ausführen?Kann ich Fehler in Axios Beitrag basierend auf dem Antwortstatus
Zum Beispiel:
axios.post('link-to-my-post-service', {
json-input
}).then(response => {
if (response.status === 200) {
//proceed...
}
else {
// throw error and go to catch block
}
}).catch(error => {
//run this code always when status!==200
});
EDIT
Ich versuchte dies, aber es hat nicht funktioniert:
var instance = axios.create({
validateStatus: function (status)
{
return status == 200;
}
});
axios.post('link-to-my-post-service', {input: myInput}, instance)
.then(response => {
dispatch({
type: "FETCH_SUCCESS",
payload: response.data
});
}).catch(error => {
dispatch({
type: "FETCH_FAILED",
payload: error
});
});
Wenn ich einen Statuscode 204 erhalten, noch die ausgeführt Block ist dann() Block anstelle des Catch-Blocks.
EDIT 2
Die richtige Antwort Vorschlag ist, diese mit Ilario suchen:
var instance = axios.create({
validateStatus: function (status)
{
return status == 200;
}
});
instance.post('link-to-my-post-service', {input: myInput})
.then(response => {
dispatch({
type: "FETCH_SUCCESS",
payload: response.data
});
}).catch(error => {
dispatch({
type: "FETCH_FAILED",
payload: error
});
});
Nun, wenn der Statuscode 200 der Blockcode Fang ausgeführt nicht gleich ist.
froh, dass es jetzt funktioniert !! –