Ajax xMlHttpRequest.responseText not display what I set (very strange!) - ajax

I have a standard Ajax call with "Success" and "error". The error part is as straightforward as:
error: function (xMlHttpRequest, textStatus, errorThrown) {
errorLabel.text("ERROR: " + xMlHttpRequest.responseText); },
And in my C# backend, I saw someone recommend to use these code:
Response.StatusCode = 409; //as long as not 200
Response.Clear();
Response.Write(msg);
Response.End();
My errorLabel successfully display xMlHttpRequest.responseText after validation ON MY LOCAL DEV MACHINE.
However when I publish everything to a WINDOWS 2012 SERVER, there is no customized 'msg' in xMlHttpRequest.responseText anymore. Instead I got "The page was not displayed because there was a conflict" in responseText. (I could understand that status code 409 means there is a conflict.)
So how come it will perform like that when on a server ?? My own error message seems to have been replaced!
Thanks a lot!
*********************** C# Code ******************
[HttpPost]
public ActionResult DoSomething()
{
if (someconditiontrue)
{
return Json(new {value1=xxxx, value2=yyy})
}
else
{
Response.StatusCode = 409; //as long as not 200
Response.Clear();
Response.Write("my customized error message");
Response.End();
}
return Content(string.Empty);
}

I worked it around by not using "error" as returned result. Instead I still use Json { error = "my customized error message") object as result, and display corresponding validation message in "success: function(result){....}" block.

Related

Service failing to correctly return status code to UI

Maybe this is silly question but I'm trying to learn Spring MVC and I have everything working except for the exceptions. So I have a simple form application where the user can register, if the user already exists I'd like to send an error code to the UI so that it knows why it failed. Heres my code:
#ResponseBody
#PostMapping("users")
public ResponseEntity addUser(#RequestBody User user) {
List<User> users = usersService.addUser(user);
if(users == null) return new ResponseEntity(HttpStatus.EXPECTATION_FAILED);
else return new ResponseEntity<>(users, HttpStatus.ACCEPTED);
}
It works fine, as in it returns a status code to the UI but the exception returns it in this string format:
Error: Request failed with status code 417
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:69)
The log above is from a console log from the UI, right after the catch below:
function register(user) {
return dispatch => {
axios.post(`${BASE_URL}/users`, user).then((response) => {
console.log(response);
dispatch(resetError());
dispatch(success(user));
}).catch((e) => {
console.log('e', e);
dispatch(error(e.status));
})
};
function success(user) { return { type: userConstants.REGISTER, payload: user } };
};
Funny enough it actually prints exactly what I'm looking for if the http call succeeds. Here's what it prints on the happy path of the promise (ACCEPTED):
Notice that it has a status property. I'd very much not like to parse a string on the UI side just to get the error code from the service. Why is the response object different? The only thing I've changed is the status code. How can I make the error status give the UI a nice object instead of a string?
If you'd like to pull the branch here is the URL: https://github.com/MatTaNg/react-form
The code snippets are in the UsersResource file
Instead of console.log('e', e) try console.log('e', e.response.status).
Source:
https://github.com/axios/axios#handling-errors

The browser overwrites the content of the message after receiving the response

I have a little problem with DingoAPI and Vue.js when I'm trying to get my error message from response. I think the browser is replacing my custom message by the default one. Here is my code:
PHP script
if($request->readerId){
Return succes (this works properly)
else{
return $this->response->error(
'No reader',
400 //(or diffrent code)
);
}
Vue.js script
await axios.post(API_URL + 'card/', {
some data
}, {
headers: {
headers
},
}).then(({data}) => {
context.commit(SET_RESPONSE, data);
}).catch((error) => {
console.log(error.message);
throw error
})
When I'm trying to look on my message in the network tab I can see (so DingoAPI did it correctly):
{"message":"No reader","status_code":400}
But when I'm using console.log(error.message) or trying to show it on the page there is standard error message:
Request failed with status code 400
Is there a way to set error message with DingoAPI and catch it in my .js script?
Maybe I need to write my own custom exception?
What you want is access to the data of the response from your error variable.
console.log(error.response.data.message); // No reader
Otherwise you can log error.response to see the object:
console.log(error.response);
If you wonder why it's printing Request failed with status code 400:
The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.
Source: https://github.com/axios/axios/issues/960#issuecomment-309287911

Custom Error Message after Datatables ajax exception

I am displaying a table of data using datatables 1.10.12. The user can specify input parameters that cause an error on the server. An appropriate error message should be displayed to the user so they can modify their setup, however the only error options seem to be:
SHow the following generic error in an alert: "DataTables warning: table id=trackingTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7"
Show the generic error in the browser console
Modify the server to return no rows, that is fail silently.
Does anyone know how to show a custom error after a datatables ajax request fails?
The following code sample is taken from the datatables documentation. Datatables handles the ajax call and handles success and error.
$(document).ready(function() {
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
A 4th option I could add to the list would be to modify the datatables source code to handle the an error response myself. Which I'm not that keen on.
This question was asked in 2015 however it did not get an answer. See:
display server side exception
If you pass an object to the ajax property you can override the jQuery.ajax() error method:
$(document).ready(function () {
$('#example').DataTable({
ajax: {
url: '../ajax/data/arrays.txt',
error: function (jqXHR, textStatus, errorThrown) {
// Do something here
}
}
});
});
https://datatables.net/reference/option/ajax#object
This will stop the standard error message in the alert box.
Please note, it is not recommended to override the success method of jQuery.ajax() as it is used by DataTables.
You can implement your own custom error message globally like the example below.
$(document).ready(function() {
$.fn.dataTable.ext.errMode = () => alert('Error while loading the table data. Please refresh');
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
});
});
Answering just in case someone is still looking for a solution.
In my case, I did the following
At server side set DataTablesOutput object.setError("ErrorMsg")
In my js method $.fn.dataTable.ext.errMode = 'none'; to avoid the error popup.
Created an error div in my page to display the custom error message
Added the below to my js method to handle error
$('#myDataTable')
.on('error.dt',
function(e, settings, techNote, message) {//Logic to set the div innertext
}
try {
$.ajax({
-------
-------
success: function (data){
//ShowDataTable is a js Function which takes ajax response data and display it.
ShowDataTable(data);
},
//this error will catch server-side error if request fails
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
ShowDataTable(null);
}
})
}
//this catch block will catch javascript exceptions,
catch (Error) {
if (typeof console != "undefined") {
console.log(Error);
ShowDataTable(null);
alert(Error);
}
}
EDIT
If you are willing to accept the error (for example if you cannot alter the backend system to fix the error), but don't want your end users to see the alert() message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it. This can be done using:
$.fn.dataTable.ext.errMode = 'throw';

Want to alert AJAX feedback responses from this.responseText

I have been trying to alert this so that it prints two responses
when there is an error or a duplicate entry and
when the response is ok and prints successfully
var response;
try {
response = JSON.parse(xmlhttp.responseText);
} catch (e) {
console.error(this.responseText);
alert(this.responseText);
}
if (response) {
console.log(response);
}
I want it to alert a response both when there is a failure and when the response is successful, but I haven't figured it out yet.
figured it out
at this stage
console.error(this.responseText);
alert(this.responseText);
i needed to insert my error message here like this
var responseText = this.responseText;
alert('Registration failure because ' + responseText );
and below
console.log(response);
alert ('Registration Successful');
At this stage it prints the required outcome.

$http error Function not showing error message

I have to give user a proper message while ajax call got fail
My Ajax call is as follows:
$http({
method:'PUT',
url:"/myapp/web/update",
crossDomain:true,
data:dataobj,
headers:{
'Content-Type':'application/json',
}
}).success(function (data) {
console.log("error"+JSON.stringify(data));
}).error(function (data, status, headers, config) {
console.log("error"+JSON.stringify(data));
});
from the backed i have used Spring MVC 4 as restfull api. From that i am validating the data and send response accordingly. If something went wrong in validation i throw custom exceptions.
Now if i throw just exception it got cached in Ajax success function but i want it to have to catch this in error function. for this i add following line of code :
response.sendError(500);
Now it got cached in error function as expected but i cant find JSON error message with it. Can anybody tell where i went wrong in the code.
Edit:
Following is the Code where i am responding with error message
#ControllerAdvice
public class ExceptionHandlingController{
#ExceptionHandler(EmployeeNotFoundException.class)
public #ResponseBody ExceptionJSONInfo handleEmployeeNotFoundException(HttpServletRequest request, Exception ex){
ExceptionJSONInfo response = new ExceptionJSONInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(ex.getMessage());
response.sendError(500);
return response;
}
}

Resources