I'm trying to do some error handling in an SPFx web part, and I can't seem to get to the inner error message of a response that's not what I'm expecting.
In the following code snippet, I've deliberately added some xxx's to the accept
header in order to get an error response. If I log it in the console, I can see it, but if I try to get to the message
property, it comes back undefined
.
private loadMyList() {
// baseUri is essentially this.props.context.pageContext.web.absoluteUrl
const { spClient, baseUri }: IMyComponentState = this.state;
const uri: string = `${baseUri}/_api/web/lists/getbytitle('${strings.MyListName}')`;
spClient.get(uri, SPHttpClient.configurations.v1, {
headers: {
'accept': 'application/jsonxxxx'
}
}).then((response: SPHttpClientResponse) => {
console.log(response.status) // with the xxx's in the header, this is 406
console.log(response.statusText) // "Not Acceptable", also, not useful
response.json().then(responseJSON => {
if (response.status === 404) {
// expected the possibility of list not found, do something else
} else if (response.status === 200) {
// expected the possibility of list found, responseJSON is the list object
} else {
// was some other error
console.log(responseJSON);
// responseJSON is an object with properties "code" and "message"
// but
console.log('message:', responseJSON.message); // undefined
console.log('has own property', responseJSON.hasOwnProperty('message')); // false
// but yet it clearly _does_ have a message property
}
});
}).catch(error => {
// do something with the error
});
}
Here's what shows up in the console:
So how do I get to that inner error message? The response.statusText
of "Not Acceptable" is not as useful as the message detailing that there's a problem with the accept
header.
response.responseText
? If it were an unextended XMLHttpRequest object I were dealing with, that's the property I'd examine.SPHttpClientResponse
class is barely an extension of theHttpClientResponse
class, for which the documentation can be found here.responseText
is not a property or method there.