I know that behaviour is probably something good,but i wrote my error messages into the Json response.It looks like the following:
{
"message": "There was a problem processing the input",
"code": 500,
"status": "INTERNAL_SERVER_ERROR",
"timestamp": "2024-04-21T00:31:17.6652992"
}
my goal is to have the "message" displayed when an error occurs,but svelte interrupts everything as soon as it sees the code 500.
This is my Svelte code at the moment:
errorHeader = 'Editing User....';
errorMessage = '';
let status;
return await fetch('http://localhost:8080/Manage-User', {
method: 'PUT',
body: JSON.stringify(mainBody),
headers: {
'Content-Type': 'application/json',
}
}).then(response =>{console.log(response);
status = response.status;
return response.json
}).then(result => {if(status>=200 && status<300){
errorHeader = "Success"
}
else if(status<=200 && status>300) {
errorHeader = "An error occured while editing the user";
errorMessage = result.message;
}})
}
When trying to enter something that is wrong i get following error message in my browser console:
PUT http://localhost:8080/Manage-User 500 (Internal Server Error)
window.fetch @ fetcher.js?v=e8991498:62
saveUser @ +page.svelte:155
Is there any way to prevent this error or a better way of doing this?
I already tried adding ).catch(error => (...))
. But this part of the code has no way of acessing the message in the response.
The promise returned from fetch()
will only reject if the communication with the server fails, so if fetch()
results in a 500
response status code, the promise will still resolve, so using .catch()
won't help you in this case. However, you should use:
response.json()
, and not response.json
And you do only handle the case status>=200 && status<300
, so you can't expect anything to happen when you receive back a 500
response.