I have a JavaScript client which makes Ajax call to a .net service (Lets call it First service). First service then makes call to another .net Controller (Call it Second Service). In this controller, I am throwing some exception. On the first line I am saying:
//Code from Second Service
[HttpPost]
public HttpResponseMessage Results(ParamsModel data)
{
throw new Exception("Exception for testing purpose");
}
//Code from First Service
[HttpPost]
public ActionResult Results(ParamsModel data)
{
var client = new HttpClient();
var task = client.PostAsJsonAsync(urlTemplate, data);
var result = task.Result.Content.ReadAsStringAsync().Result;
return Content(result, "application/json");
}
Problem: Though the Second Service is throwing error & returning 500 status code, The first servcie returns 200 status code to the JavaScript client. I am also not able to read the satus code returned by Second service as I only get string output.
Please suggest. I want to return 500 status code when there is an error.
You can implement error handling as follows in the HttpClient.
Hope this helps.
You can return a HttpResponseException like this:
You will need to throw the right exception from your WebAPI controller:
There are several status codes that can be thrown:
https://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx
Why can't you do an asynchronous action method?
But the thing is, with the layout of the first method it doesn't matter how you handle exceptions in the second one, as the first will always return "Internal Server Error".
To make it useful, you should typically return different error codes in the first method too.