Share via

Error Handling in .net6 minimal API

Newbie Dev 156 Reputation points
2022-01-17T09:51:46.78+00:00

Hi,
I am working on a project which uses minimal API.
The project has a only 2 endpoints, GetAllItems and GetItem(with id).

For the get all item the code is,

app.MapGet("/items", ([FromServices] ItemRepository items) =>
{
    return items.GetAll();
});

For the getItem endpoint the code is,

app.MapGet("/items/{id}", ([FromServices] ItemRepository items, int id) =>
{
    var result = items.GetById(id);
    return result != null ? Results.Ok(result) :  Results.NotFound();
});

So, for getItem(id) the result is checked against null and returned result accordingly.

Is it necessary to do error checking for GetAllItems()?

In all the examples I saw, none of them is doing error checking for GetAllItem kind of endpoints.

Is there a general rule? What if the database is errored or a network failure happens when getting the GetAllItems? How will it be handles in the above code?

Developer technologies | ASP.NET Core | Other
0 comments No comments

Answer accepted by question author

Anonymous
2022-01-18T05:34:37.51+00:00

Hi @Newbie Dev ,

Is it necessary to do error checking for GetAllItems()?

Yes, it is necessary. To prevent the application stop/exit because of the inner exception.

Is there a general rule? What if the database is errored or a network failure happens when getting the GetAllItems? How will it be handles in the above code?

When get data from the repository or database, you can use Try-Catch statement to capture the exception, then in the catch block, you can create the error model based on the exception message, and then return the error message to the client. Code like this:

app.MapGet("/items", ([FromServices] IDataRepository items) =>  
{  
    try  
    {  
        return Results.Ok(items.GetAll());  
    }  
    catch (Exception ex)  
    {  
        //there have an exception to query data from the the Repository.  
        return Results.Ok(new { ErrorMessage = ex.Message });  
    }  
});  
  
app.MapGet("/items/{id}", ([FromServices] IDataRepository items, int id) =>  
{  
    try  
    {  
        var result = items.GetEmployeeByID(id);  
        return result != null ? Results.Ok(result) : Results.NotFound();  
    }  
    catch (Exception ex)  
    {  
        return Results.Ok(new { ErrorMessage = ex.Message });  
    };  
});  

Besides, you can also provide a lambda to UseExceptionHandler. Like this:

var app = builder.Build();  
  
app.UseExceptionHandler(exceptionHandlerApp =>  
{  
    exceptionHandlerApp.Run(async context =>  
    {  
        context.Response.StatusCode = StatusCodes.Status500InternalServerError;  
  
        // using static System.Net.Mime.MediaTypeNames;  
        context.Response.ContentType = Text.Plain;  
  
        await context.Response.WriteAsync("An exception was thrown.");  
  
        var exceptionHandlerPathFeature =  
            context.Features.Get<IExceptionHandlerPathFeature>();  
  
        if (exceptionHandlerPathFeature?.Error is FileNotFoundException)  
        {  
            await context.Response.WriteAsync(" The file was not found.");  
        }  
  
        if (exceptionHandlerPathFeature?.Path == "/")  
        {  
            await context.Response.WriteAsync(" Page: Home.");  
        }  
    });  
});  

Or create a custom middleware to hand the error. Refer to the following articles:

Exception handler lambda

Implement Global Exception Handling In ASP.NET Core Application

ASP.NET Core Web API exception handling


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,086 Reputation points
    2022-01-17T15:44:44.313+00:00

    It depends on what error handling middleware you enabled. If none then the program will error exit. See docs

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.