When I create this .NET 5 Web API which returns an error via "NotFound" but includes text string with additional error information, this custom error details:
(a) shows up in Postman in the response body, however
(b) I can’t see the error info it in the "caught" error in my React Axios code (see below)???
How can I get access to such detailed error message from a .NET 5 web api? The "axios.post" request is working fine, just when I simulate an error state I’m trying to pick up extra error information to the client I want to pass back.
API CODE (.NET 5)
var errorDetails = new
{
error = "Custom error",
message = "Custom message",
details = "Custom details"
};
var errorDetailsJson = JsonSerializer.Serialize(errorDetails);
return NotFound(errorDetailsJson);
REACT / AXIOS CODE
try {
let response = await axios.post(url, body, await getCustomAuthOptions('POST'));
let data = await response.data;
return data as T;
} catch (error) {
console.log(error.toJSON()); // I CAN'T SEE THE RESPONSE BODY WITH CUSTOM ERROR MESSAGES HERE
throw error;
}
RESULT OF console.log FROM THE CATCH
{
"message": "Request failed with status code 404",
"name": "Error",
"stack": "Error: Request failed with status code 404n ...cut",
"config": {
"url": "https://localhost:5001/THE_URL_I_USE",
"method": "post",
"data": "",
"headers": {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer xxxetc"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"mode": "cors"
}
}
2
Answers
As @Greg already pointed out. You can get the response information from the exception itself. See example:
It is an axios error so you can handle it this way :