Reputation: 33
I am trying a post request to http://localhost:5000/run. If the server is not running then trying to throw "Please retry again" to client.
try{
const {data} = await axios.post("http://localhost:5000/run",payload);
setOutput(data.output);
}
catch ({ response }) {
if (response) {
const errMsg = response.data.err.stderr;
setOutput(errMsg);
} else {
setOutput("Please retry submitting.");
}
}
when the server is running proper error is received but not when the server is offline. Anything missing from the code?
Upvotes: 2
Views: 3959
Reputation: 33
Thank you for all the comments, this is the solution that ended up working:
try {
const {data} = await axios.post("http://localhost:5000/run", payload);
setOutput(data.output);
} catch (error) {
if (error.response.data) {
setOutput(error.response.data.err.stderr);
} else {
setOutput("Error connecting to the server!");
}
}
Upvotes: 0
Reputation: 285
Please try this code:
import axios from "axios";
import {AxiosError} from 'axios';
axios
.post("http://localhost:5000/run", payload)
.then((response) => setOutput(response.data.output))
.catch((error) => {
if (!error?.response) {
setOutput("No Server Response");
} else if (error?.code === AxiosError.ERR_NETWORK) {
setOutput("Network Error");
} else if (error.response?.status === 404) {
setOutput("404 - Not Found");
} else if (error?.code) {
setOutput("Code: " + error.code);
} else {
setOutput("Unknown Error");
}
});
You can use axios.isAxiosError(error)
to make sure that the error is type of AxiosError.
Axios error types:
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
static readonly ERR_NETWORK = "ERR_NETWORK";
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
static readonly ERR_CANCELED = "ERR_CANCELED";
static readonly ECONNABORTED = "ECONNABORTED";
static readonly ETIMEDOUT = "ETIMEDOUT";
Upvotes: 2
Reputation: 4614
You need to try using response.response.data.error
for displaying error in your case instead of response.data.err.stderr
. So here you are getting error data from response :
try{
const {data} = await axios.post("http://localhost:5000/run",payload);
setOutput(data.output);
}
catch ({ response }) {
if (response) {
const errMsg = response.response.data.error;
setOutput(errMsg);
} else {
setOutput("Please retry submitting.");
}
}
Reference discussion here.
Upvotes: 0