Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 5 ajax error statusText is always "error"

I'm having a problem sending a custom message on error to an ajax call. My controller returns something like this:

return new HttpStatusCodeResult(400, "My error!");

And my ajax code looks like this:

error: function (xhr, httpStatusMessage) {
              console.log(xhr.statusText);
              console.log(httpStatusMessage);
}

The problem is that xhr.statusCode and httpStatusMessage is always "error". What am I doing wrong now? I'm expecting to have "My error!" in xhr.statusText.

I'm using ASP.NET MVC 5 and jquery-1.10.2

My xhr output is:

abort:ƒ ( statusText )
always:ƒ ()
complete:ƒ ()
done:ƒ ()
error:ƒ ()
fail:ƒ ()
getAllResponseHeaders:ƒ ()
getResponseHeader:ƒ ( key )
overrideMimeType:ƒ ( type )
pipe:ƒ ( /* fnDone, fnFail, fnProgress */ )
progress:ƒ ()
promise:ƒ ( obj )
readyState:4
responseText:"Bad Request"
setRequestHeader:ƒ ( name, value )
state:ƒ ()
status:400
statusCode:ƒ ( map )
statusText:"error"
success:ƒ ()
then:ƒ ( /* fnDone, fnFail, fnProgress */ )

My Web.config httpErrors configuration looks like this:

<httpErrors existingResponse="PassThrough" errorMode="Custom">
      <remove statusCode="404" />
      <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
      <remove statusCode="403" />
      <error statusCode="403" path="/Error/Forbidden" responseMode="ExecuteURL" />
    </httpErrors>

and still, on my dev environment, the responseText is empty and the statusText is just "error".

like image 280
Robert Avatar asked Jan 27 '26 04:01

Robert


1 Answers

You need to set a property in your Web.Config file.

Citing a user of this web page on github, emphasis mine,

By default IIS will mask your error codes and replace them with default errors. The "PassThrough" option tells IIS to leave your custom errors alone and render them as-is.

"Bad Request" is the default http error text for the status code 400.

So there is the setting as documented here and outlined here,

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
  </system.webServer>
</configuration>

Consult the documentation carefully for your version of IIS, there is lots of subtle version differences.

EDIT

Not really specific to MVC, but it is how I once solved it (part of production code), and what seems to have helped OP as well:

Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
Response.Write(new String('_', 513) + "my custom message");

This absurd minimum character limit thing may or may not be needed depending on IIS version. I would too be grateful if somebody could shed a little more light on this underdocumented behavior.

like image 115
Cee McSharpface Avatar answered Jan 28 '26 17:01

Cee McSharpface