emboole
emboole

Reputation: 571

How can i get logs/debugging for an error 500?

I'm working on a .NET Core 2.0 web application. I got a mocked database where application works good. Today i created a clean database and got this error 500 both on IIS Express and on regular IIS. The thing is: i couldn't debug why is throwing the error 500. The application just run.

I've currently tried:

Hosting environment: Production Content root path: C:\Users\pistolon\Downloads\peto Now listening on: http://localhost:13361 Application started. Press Ctrl+C to shut down.

When I switch back to the mocked db it works without error.

Do you any of you could point me on where could i get an exception or log for this?

Upvotes: 3

Views: 4507

Answers (2)

user7758647
user7758647

Reputation:

I don't believe this is enough information to go off of, however if you're seeing that 500 error when using the real database and the mock database is working appropriately, I would bet that your issue is with the connection string. You can also check to ensure that you're in the development environment as well.

Update: You can also try to use app.UseDeveloperExceptionPage();

Upvotes: 2

Moien Tajik
Moien Tajik

Reputation: 2321

You can use Event Viewer or Visual Studio Remote Debugging to debug your deployed applications.

Also, you can use a logging framework like Serilog and use one of it sinks like file sink and create a middleware which catches and logs your exceptions and write their StackTrace, Message, Source to a log file that you can read them.

Here is ErrorHandlingMiddleware implementation :

public class ErrorHandlingMiddleware
{
    readonly RequestDelegate _next;
    static ILogger<ErrorHandlingMiddleware> _logger;

    public ErrorHandlingMiddleware(RequestDelegate next,
        ILogger<ErrorHandlingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    static async Task HandleExceptionAsync(
         HttpContext context,
         Exception exception)
    {
        string error = "An internal server error has occured.";

        _logger.LogError($"{exception.Source} - {exception.Message} - {exception.StackTrace} - {exception.TargetSite.Name}");

        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        context.Response.ContentType = "application/json";

        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
        {
            error
        }));
    }
}

Usage :

app.UseMiddleware<ErrorHandlingMiddleware>();

Upvotes: 4

Related Questions