I have a project using ASP.NET Web API 2.0 and a method in this API throws an exception:
public void TestMethod()
{
throw new Exception("Error40001");
}
When this exception was thrown, I made a handler to handle these things:
public class APIExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var rm = Language.Error.ResourceManager;
string message = rm.GetString(context.Exception.Message);
string detailed = "";
try
{
detailed = rm.GetString(context.Exception.Message + "Detailed");
}
catch
{
if (String.IsNullOrEmpty(detailed))
{
detailed = message;
}
}
HttpStatusCode code = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), context.Exception.Message.Replace("Error", "").Substring(0, 3));
context.Result = new ResponseMessageResult(context.Request.CreateResponse(code,
new ErrorInformation() { Message = message, DetailedMessage = detailed }));
}
}
public class ErrorInformation
{
public string Message { get; set; }
public string DetailedMessage { get; set; }
}
The problem is that when I get this error, this is not the same status code that I installed it on. The handler picks it up and creates the result of the response message with error code 400.
Here you see the result that returns with status code 400

But when I get an error in the browser, the status code has changed
Here you see the status code that is returned

And content

As you can see in the last figure, the content from the processed exception is at the beginning, but the error message is turned on by default and the status code has been overwritten.
, , webconfig, . ? - ?