Handling server side errors in javascript fetch - javascript

I'm making a script which has server side validation. When validation fails I have the script throw an exception server side. I want to access the message in the exception when the response reaches the client side, but I'm having trouble with that. If I console.log the data I can see the exception, but I want to access it in the catch so I can push the error message to an HTML element on the page.
fetch(/* Posting to some PHP script */).then(function(data) {
// Logic here when success
console.log(data) // Shows error msg when there is an error
}).catch(function() {
// Error Handling, I want to push the error msg to HTML element here
});
What am I doing wrong here?
Thanks

Throw the error. It will be caught in the .catch() and you can manipulate it there
fetch(/* Posting to some PHP script */)
.then(function(data) {
// Logic here when success
console.log(data) // Shows error msg when there is an error
if(data.error){ // Or whatever condition you need to detect there's an error
throw data.error; // This will be caught in the catch() below
}
})
.catch(function(err) {
// You have your error here with the message from the server, display it in the HTML
});

Related

How to catch specific error message in javascript from backend

From backend I am getting specific error message during the post request. How may I get this message in javascript?
catch(err => console.log('error', err.response.data))
With this code I am getting just the type of the error, but I need the message which I throw from backend. F.ex throw ConflictException("The name is already exist"). I need get the following message "The name is already exist", not just the the type.
<!DOCTYPE html>
<html>
<body>
<script>
try {
throw new Error('Custom Exception');
}
catch(err) {
if(err.message){
console.log('inside if & error message as follow : ',err.message);
}else {
console.log('inside else');
console.log(err);
}
}
</script>
</body>
</html>
Above is for demonstration purpose, if it still not working then try
catch(err => console.log('error', err?.message));
Caught errors generally have a message field stored at error?.message or if you using things like Axios or other API requests, error messages are generally at error.response?.data?.message!
Note: ?. is an optional chaining to prevent other errors like Can not read properties of undefined, reading x

How to handle 404 error in a async/await?

When fetching postcode from Postcode io API, I tried this error handling code:
async getCoord() {
const postcodeAPI = `http://api.postcodes.io/postcodes/dt12pbbbbbbbbb`;
let response;
try {
response = await fetch(postcodeAPI);
}
catch (e) {
console.log(e);
};
};
The fetch method returns a 404 error as postcode is invalid. In my understanding the try block should be tried and skipped and the error should be caught by the catch method, but instead I got this red 404 error in console:
which happens in the try block, and is the same as no error handling in the code. Why does this happen? Is it because this is browser default behaviour? Is there a way to improve the error handling here?
EDIT
What I wanted was the red console error to disappear and show my own error information instead, but the console error seems unavoidable.
Fetch API doesn't throw errors on any status code. It only throws errors on network failures, i.e. when it couldn't finish the request itself.
You can use response.ok to check if the request finished with 2XX status code.
async getCoord() {
const postcodeAPI = `http://api.postcodes.io/postcodes/dt12pbbbbbbbbb`;
let response;
try {
response = await fetch(postcodeAPI);
if (!response.ok) throw new Error('Request failed.');
}
catch (e) {
console.log(e);
};
};
You can also explicitly check the status code if you need:
if (response.status === 404) {
// handle 404
}
As for your question about logging 404 errors in the console, there's no way or need to avoid it. Whenever you make a request, it's being logged in the dev tools. But dev tools are just what they are called - tools for devs. You can safely assume your users won't look there and even if someone does, having 404 there is not the end of the world.

Reading the error value in Javascript

I am handling the error in a if block in the method where I receive the response from the server. I put the server down in order to test the service unavailable scenario
_onResponse: function (err, res) {
if (err){
}
on doing alert("error " + err);
I receive
Error: Request has been terminated
Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.
at Request.crossDomainError (http://localhost:9000/index.js:33875:14)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:9000/index.js:33945:20)
I want to read the value of Error:
I tried doing err.message but then I receive the entire body of the error.
I tried with err.name I just get the text 'Error'
How do I get the content Request has been terminated in a javascript variable?
From the response all I can say is this is not the error your server is sending. It is raised by the engine while doing XHR to a domain for which CORS is disabled. To catch this error, wrap the XHR code in index.js around line 33945 in a try{} catch(e){} block. Inside catch block you get hold of the error using the e variable.
Your block will handle error only when you get a response from the target server.

Purposefully Invoke an Error in $http Post Request

I'm using Angular to send a post request with the $http service. I am doing all of the data validation of the form in Angular prior to sending the post request. However, there is one validation I am doing in PHP of whether the user already exists in the database. How do I purposefully invoke an error (in the php file) so that the Angular error callback is triggered instead of the success callback? Should I purposefully throw an exception?
IF the intent is to throw an exception, does the exception message get passed into the data parameter for the Angular error callback function?
Based on the comments to my question, I just did the following to my code:
if (duplicateUsers($username) > 0) {
return http_response_code(400); // successfully generated an error in
// the $http AngularJS servicces
} else {
// other code
}
You can chain your promises. The first promise will check the success content and that's also where you can throw an exception. This will cause the subsequent promises to return failure.
Here's a jsbin example.
angular
.module('app', [])
.run(function($http) {
var from$http = $http
.get('www.google.com') //makes a request to www.google.com
.then(function(response) {
console.log('data was successfully retrieved from google');
throw "from success handler"; //if has error, then throw "duplicated user"
});
from$http.then(function() { // this then block is handling the previous exception
console.log('this success block is never called');
}, function() {
console.log('inside error block even tho success was returned from www.google.com');
});
});

How to deal with an uncaught exception error in Meteor?

How do I listen to an uncaught exception error in meteor?
The errors are of course specific to the cause, so please can you provide a pseudo style code/explanation that states the concept of handling this error.
An example use case:
A user clicks 'logout' but there is an uncaught exception and the user does not get logged out and so the connection to the server remains open.
You can use the callbacks, they usually provide a reason parameter. E.g
Meteor.call("some_random_non_existent_method", function(err, result) {
if(err) return alert(err.reason)
});
Most meteor callbacks have a error param. With the logout its Meteor.logout(function(err) { ... })
You should be able to catch most types of errors like this. If you want to capture all errors you can use try..catch. Everything in the try block will try to run until it throws an error. You can catch this and provide feedback to the user.
try {
//This will throw an error
this.run_something.go_make_error()
}catch(e) {
alert("There was an error running this");
}

Categories