I have a custom middleware class in asp.net web api which processes and sends a response to the client. It is class controller action which actually return a response.
During execution of this GetT function in controller it breaks and returns a ninternal server error 500. We want to handle the internal error 500 and what the exception type was. We still want to send status code 500 error but with a custom error message in the original Response.
Class TResponse, apart from sending data, also sends whether it succeeds or not and some other message can be set if there was a 500 error. But we still want to send this TResponse even after 500 error.
Controller/Action:
public async Task<ActionResult<TResponse>> GetT(TRequest request)
{
.............
TResponse response = await _tService.GetT(request);
.......
return Ok(response).
}
public class ResponseMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var originalBodyStream = context.Response.Body;
try
{
using var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
await next(context);
memoryStream.Position = 0;
var reader = new StreamReader(memoryStream);
var responseBody = await reader.ReadToEndAsync();
memoryStream.Position = 0;
await memoryStream.CopyToAsync(originalBodyStream);
var requestTelemetry = context.Features.Get<RequestTelemetry>();
requestTelemetry?.Properties.Add("ResponseBody", responseBody);
Log.Information(responseBody);
}
catch (Exception ex)
{
string exType = ex.GetType().ToString();
context.Response.StatusCode = 500;
if (exType=="sql") //Data query error
{
context.Response.ContentType = "application/json";
TResponse response = new TResponse();
// ???????????
}
finally
{
context.Response.Body = originalBodyStream;
}
}
}
So in the catch block of the InvokeAsync(), I added a try catch block to handle 500 error. I am facing a challenge how to convert a TResponse (after settiing some info on it for 500 related error) object into original body response which somehow gets processed through memory stream just like when there is no error.
In Short, how to handle 500 error and send TResponse from catch block?
I think we want to execute the same line of code in InvokeAsync() even after handling 500 error in order to send correct response.