A set of technologies in .NET for building web applications and web services. Miscellaneous topics that do not fit into specific categories.
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:
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