I have an API to update data to the database.
I am using Fetch API to send data to the server API for storing data in the database.
In case the webserver cannot update data to the database, it returns a 500 error code and an error message.
And the response JSON as the following:
{"status":"error","message":"Some wrong when update roster data."}
My problem is that I cannot forward the message to the fetch API caller.
It is my fetch API source code:
static async fetchAPI(url,method,getParams,postParams){
if (getParams){
const paramsObject = new URLSearchParams(getParams);
const queryString = paramsObject.toString();
url+="?"+queryString;
}
url="/rosterWeb"+url;
console.log("=======================");
console.log("url="+url);
console.log("method="+method);
console.log("getParams="+getParams);
console.log("postParams="+postParams);
console.log("=======================");
return fetch(url,
{
body: JSON.stringify(postParams),
headers:{
'Content-Type': 'application/json'
},
"method":method || 'GET',
})
.then(response =>{
if (response.ok){
return response.json();
} else {
if (response.status===500){
response.json()
.then(json=>{
throw new Error(json.message);
})
}
}
})
.catch(error =>{
console.error('Error:', error);
});
}
This is my middleware code snippet:
import Utility from './Utility';
export default class Roster{
..............
.......
constructor(){
this.saveToDB=async(data)=>{
return await Utility.fetchAPI(*saveDataURL*,POST',null,rosterData);
}
}
}
This is my UI component code snippet:
export default function ButtonPanel(){
..............................
async function saveDataToDB(){
let roster=new Roster();
await roster.saveRosterToDB({
........................
...........................
})
.then(result=>{
console.log("Update Success")
})
.catch(error=>{
console.log("ButtonPanel Exception Caught");
console.log(error);
})
/*
try{
let result=await roster.saveRosterToDB({
month:rosterMonth.getMonth()+1,
preferredShiftList:rosterData.preferredShiftList,
rosterList:rosterData.rosterList,
year:rosterMonth.getFullYear(),
})
console.log(result);
}catch(error){
console.log("Exception caught.");
console.log(error.message);
};
*/
roster=null;
}
}
When I execute the Roster.saveRosterToDB method, both try-catch and then-catch structure, it also returns the following error:
`Unhandled Rejection (Error): Some wrong when update roster data.
(anonymous function)
c:/Users/knvb/workspace/rosterWeb_react_node/src/utils/Utility.js:91`
Where "Some wrong when update roster data" is come from response JSON.
And the ButtonPanel.saveDataToDB print the statement "Update success" to the console.
I tried to forward the message from the server to ButtonPanel via an exception.
However, the exception/error does not be triggered, how can I fix it?