Hi,
When we hit the swagger docs url localhost:xxxswaggerdocsapi-version, we get a 500 error. But there are no traces - no stack trace, no other helpful information. How to debug this? Is there a place where logs are displayed. I've found in other issues that they at least got stack traces, with which they were able to debug the issues. This is the not the case with us. I've even tried the step suggested in http://stackoverflow.com/a/39238793 but of no avail. We are clueless as to how to debug this, can someone from the team help?
Thanks!
+1
This is very frustrating!
I found a solution.
Use Middleware. This is my unmodified implementation which you can adapt.
public class ErrorHandler
{
private readonly RequestDelegate next;
private readonly IHostingEnvironment _env;
private readonly ILogger<ErrorHandler> _logger;
public ErrorHandler(RequestDelegate next, ILogger<ErrorHandler> logger, IHostingEnvironment env)
{
this.next = next;
_env = env;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch(Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var code = HttpStatusCode.InternalServerError;
var result = JsonConvert.SerializeObject(new { Code = code, Error = exception.Message, StackTrace = exception.StackTrace });
if(exception is BadRequestException)
{
code = HttpStatusCode.BadRequest;
result = exception.Message;
_logger.LogInformation($"Bad Request: {exception.Message}");
}
else if (exception is ResourceNotFoundException)
{
code = HttpStatusCode.NotFound;
result = exception.Message;
_logger.LogInformation(exception.Message);
}
else if (exception is UnauthorizedException)
{
code = HttpStatusCode.Unauthorized;
result = exception.Message;
_logger.LogInformation(exception.Message);
}
else
{
_logger.LogCritical(new EventId(666, "TheAntiChristCometh"), exception, exception.Message);
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
#if DEBUG
//only show in debug during development
if(_env.IsDevelopment())
return context.Response.WriteAsync(result);
#endif
return context.Response.WriteAsync("");
}
}
public static class ErrorHandlerExtension
{
public static IApplicationBuilder UseErrorHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ErrorHandler>();
}
}
then register
//register middleware before mvc
app.UseErrorHandler();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUi(c =>
{
...
});
app.UseMvc();
Most helpful comment
I found a solution.
Use Middleware. This is my unmodified implementation which you can adapt.
then register