I have created a class (using tutorials) which serves as a global middleware class to catch and handle all errors in one place:
using System.Net;
namespace WebApi.Helpers
{
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
string result = "";
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.BadRequest;
await response.WriteAsync(result);
}
}
}
}
The above code is invoked in the expected manner:
throw new AppException("error has occurred");
After reading several topics on the subject of middleware, I am understanding that the middleware class is acting upon a request in a pipeline of requests and then handing over to the next module in the pipeline to handle the request.
However in the Invoke method above, I do not understand the following:
try
{
await _next(context);
}
Is this calling the next request in the pipeline or the current one? I am basically having trouble understanding how throwing an exception elsewhere is being intercepted and processed in the Invoke method.