I want to be in control of the details of all Exceptions that occured in my web application. I want to add custom data to the exception. I also want to add more info if in debug mode. I do want to pass this as a JSON format to the user.
To do this, I want to throw an exception with an custom error code, and pass the innerexception for debug purposes.
In my startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware(typeof(ErrorHandlingMiddleware)); // Error handling middlware
....
In my service I throw an Exception:
catch (Exception e)
{
throw new Exception("E18", e.InnerException);
}
When I debug this. I can see e.InnerException is filled with data.
Here comes the magic... well... sort of. This is the middleware:
public class ErrorHandlingMiddleware
{
static Dictionary<string, APIMessageDetails> responseMessageCodes = new Dictionary<string, APIMessageDetails>
{
...
{"E18", new APIMessageDetails {responseMessage = "An unknown error occured.", httpStatusCode = StatusCodes.Status500InternalServerError}},
...
}
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try {
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
string errorCode = ex.Message;
APIMessageDetails result;
APIMessage apiMessage = new APIMessage();
if (errorCode != null)
{
if (responseMessageCodes.TryGetValue(errorCode, out result))
{
apiMessage.responseMessageCode = errorCode;
apiMessage.messageDetails = result;
#if DEBUG
apiMessage.messageDetails.exception = ex;
#endif
}
}
var jsonResult = JsonConvert.SerializeObject(apiMessage);
context.Response.ContentType = "application/json";
context.Response.StatusCode = apiMessage.messageDetails.httpStatusCode;
return context.Response.WriteAsync(jsonResult);
}
}
When I debug, I can see that the exception that is catched in the middleware, does contain the E18, but the innerException is null. I do not understand why that is; it is passed to the Exception that is thrown...
I hope someone could help me out here.
Oeps... seems like everything was okay whit the code above. Seems there is some middleware that causes double requests...
Have to figure that out, but by disabling the middleware the innerException has been filled.
Thanks all.