Home > Mobile >  Whats the best way to catch exceptions in the endoints for a dotnet app?
Whats the best way to catch exceptions in the endoints for a dotnet app?

Time:08-04

This question is going to be a bit generic, but i've been doing error handling in the entrypoint for my endpoints.

for example lets suppose we have something like this

[HttpGet]
[Route("xpto")]
public async Task<IHttpActionResult> xpto([FromUri] string id)
{
try
{
...
}
catch(Exception ex)
{
//i can throw a specifc exception and message
}
}

But since this is something that i do for all endpoints, shouldn't this be instead an Attribute/Filter configured for the http pipeline instead?

I know that for dotnet we can configure global filters that are defined for all requests.

CodePudding user response:

I guess you are focusing at the HTTP Status code 500 (Internal server error). In that case check the documentation: https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0 and https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0#exception-handler-lambda otherwise if you want to process the exception into the method body and rethrow a new exception and message this is specific for every method.

CodePudding user response:

You could have a method in a base controller to take the leg work out of it:

protected async Task<IHttpActionResult> ProcessRequest(Func<Task<IHttpActionResult>> func)
{
   try
   {
       return await func(a);
   }
   catch(Exception ex)
   {
       // return bad request
   }
}

(with overloads for different amounts of parameters, or however else you want to handle it)

call thusly:

[HttpGet]
[Route("xpto")]
public async Task<IHttpActionResult> xpto([FromUri] string id)
{
   return await ProcessRequest(() =>
   {
       // Happy-path code here
   });
}
  • Related