I have code like:
try {
LoadingStart();
const result = await $.ajax({
type: 'Get',
url: url,
data: data,
});
LoadingEnd();
window.location.replace(result.redirectUrl);
} catch (err) {
LoadingEnd();
console.error('MyFunction', err);
}
The exception, when logged comes out like
Object { readyState: 0, getResponseHeader: getResponseHeader(a), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(a, b), overrideMimeType: overrideMimeType(a), statusCode: statusCode(a), abort: abort(a), state: state(), always: always(), catch: catch(a), … }
How do I get the detail of an await AJAX exception?
I have tried 'err.message' but it seems to be undefined. I was expecting a text showing the error reason. I found detail by not using await with try/catch, instead using the AJAX error function that takes in the xhr and the exception. I would like the same kind of detail in the exception caught.
I have code like:
try {
LoadingStart();
const result = await $.ajax({
type: 'Get',
url: url,
data: data,
});
LoadingEnd();
window.location.replace(result.redirectUrl);
} catch (err) {
LoadingEnd();
console.error('MyFunction', err);
}
The exception, when logged comes out like
Object { readyState: 0, getResponseHeader: getResponseHeader(a), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(a, b), overrideMimeType: overrideMimeType(a), statusCode: statusCode(a), abort: abort(a), state: state(), always: always(), catch: catch(a), … }
How do I get the detail of an await AJAX exception?
I have tried 'err.message' but it seems to be undefined. I was expecting a text showing the error reason. I found detail by not using await with try/catch, instead using the AJAX error function that takes in the xhr and the exception. I would like the same kind of detail in the exception caught.
Share Improve this question asked 4 hours ago Kevin BurtonKevin Burton 112 bronze badges 2 |1 Answer
Reset to default 1When using await $.ajax(...)
, a failure doesn’t throw a typical JavaScript Error object but instead rejects with the jqXHR object returned by jQuery. That object doesn’t include a standard message property, so trying to access err.message returns undefined.
To get the error details, inspect the jqXHR object’s properties. For example:
err.status – The HTTP status code (e.g., 404, 500). err.statusText – The corresponding status text (e.g., "Not Found", "Internal Server Error"). err.responseText – The text of the response from the server (often contains the error message). You can modify your catch block like this:
catch (err) {
LoadingEnd();
console.error('AJAX error:', err.status, err.statusText);
console.error('Response:', err.responseText);
}
LoadingEnd()
call (or something like it) probably should be in afinally
clause. – Pointy Commented 3 hours ago