I've added Serilog to my project:
.UseSerilog((provider, context, loggerConfiguration) =>
{
loggerConfiguration
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
.WriteTo.MSSqlServer(output, tableName: "Log", schemaName: "WPS")
.Enrich.WithAspnetcoreHttpcontext(provider)
.Enrich.WithExceptionDetails();
});
I've also added a service for handling API errors returned to the UI:
// Add Error Handling to all API endpoints
services.AddMvc(options => {
options.Filters.Add(new ApiExceptionFilter());
});
public class ApiExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
ApiError apiError = null;
if (context.Exception is ApiException)
{
var ex = context.Exception as ApiException;
context.Exception = null;
apiError = new ApiError(ex.Message);
apiError.Errors = ex.Errors;
context.HttpContext.Response.StatusCode = ex.StatusCode;
}
else if (context.Exception is UnauthorizedAccessException)
{
apiError = new ApiError("Unauthorized Access");
context.HttpContext.Response.StatusCode = 403;
}
else
{
string msg = context.Exception.GetBaseException().Message;
#if !DEBUG
string stack = "";
#else
string stack = context.Exception.StackTrace;
#endif
apiError = new ApiError(msg);
apiError.Detail = stack;
context.HttpContext.Response.StatusCode = 500;
}
context.Result = new JsonResult(apiError);
base.OnException(context);
}
}
However, after adding the ApiExceptionFilter, exceptions are not logged anymore.
I have have tried throwing the exception again, but then my custom message is not returned to the UI anymore.
base.OnException(context);
throw context.Exception.GetBaseException(); // throw again?
Any suggestions on where I'm going wrong?
Your best bet, here, is to catch and filter out the exception as you're doing, here, but also to log it in your exception filter.
Generally the code the catches and handles an exception is responsible for logging it; that's what's happening without the filter - top-level exception handler is catching and logging the exception. Once you start handling the exception yourself, you're also responsible for logging it.