Reputation: 27
Hi I need to catch exceptions for http requests, e.g.:
[HttpPost("Test")]
public async Task<ActionResult<TestResponse>> Test(TestRequest request)
{
TestResponse result;
try
{
// call 3rd party service
}
catch(exception ex)
{
result.Errorcode = "Mock" // This Errorcode will be used by client side
}
return Ok(result);
}
now since there are many http requests, I want to use a middleware to globally handle exceptions rather than
writing try-catch statement in each http request as above.
public class Middleware
{
readonly RequestDelegate next;
public Middleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await next(httpContext);
}
catch (Exception ex)
{
// is there a way to pass TestResponse here so I can do result.Errorcode = "Mock"?
}
}
}
I do not know how to assign Errorcode using the middleware approach as I comment out above. Is it possible? Thanks.
Upvotes: 1
Views: 848
Reputation: 1026
If I understand your requirements well I suggest this:
You don't need access TestResponse and you can configure your response in middleware.
public class FailResponseModel
{
public FailResponseModel(string errorCode, object errorDetails)
{
ErrorCode = errorCode;
ErrorDetails = errorDetails;
}
public string ErrorCode { get; set; }
public object ErrorDetails { get; set; }
}
public class ExceptionHandlerMiddleware
{
readonly RequestDelegate next;
public Middleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await next(httpContext);
}
catch (Exception ex)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
httpContext.Response.ContentType = "application/json";
var response =
JsonConvert.SerializeObject(new FailResponseModel("your-error-code", "your-error-details"));
await httpContext.Response.WriteAsync(response);
}
}
}
Upvotes: 2