In ASP.NET MVC 5 I make a client (JavaScript) ajax request, and in case of receiving an error message from the API, I want to send this message to the client
I am using error handling in the config file:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="400"/>
<remove statusCode="403"/>
<remove statusCode="404"/>
<remove statusCode="500"/>
<error statusCode="400" path="/SystemPages/OtherError" responseMode="ExecuteURL"/>
<error statusCode="403" path="/SystemPages/Login" responseMode="Redirect"/>
<error statusCode="404" path="/SystemPages/NotFoundError" responseMode="ExecuteURL"/>
<error statusCode="500" path="/SystemPages/InternalServerError" responseMode="ExecuteURL"/>
</httpErrors>
And I have an error handling in the filter:
public class ExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
...
In JavaScript code, I am displaying an error if the response code does not match 2XX:
$.ajax({
type: "POST",
url: '/api/xxx',
data: JSON.stringify({ ids: invoiceIds }),
contentType: "application/json",
success: function (data) {
successToast("Success result ....bla bla bla.", "Success");
window.location.reload(false);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
let errorMessage = errorThrown;
if (XMLHttpRequest.responseText != null && XMLHttpRequest.responseText != '') {
errorMessage = XMLHttpRequest.responseText;
}
errorToast(errorMessage, "Error");
}
});
The problem is this: if I receive an error from the API (for example, with a status code = 400), I can process it in the filter, and I want to send a server response to the client with the same error code and error text in the response body. But in this case (due to the error code = 400) the module httpError is triggered and inserts its view into the response. And I am losing the original error description text message.
Maybe you can
a) somehow stop the operation of the httpErrors
module in a particular case, or
b) somehow pass the message I need to the controller code that is called by the httpErrors
module?