What is the best way to return errors in api controllers?
What is the best way to return errors in asp.net core api controllers?
i currently use
But are the better ways to do it?
3 Replies
for some statuses there are already premade methods (like there is one for
Ok()
)
but apart from that, it depends how they are being usedim not taling about http status code but rather just errors in general.
lets say i got a endpoint for registering a user. but it first checks if the username isnt already taken.
how do i best return that error in case the username is already taken?
There are many way to handle that.
Here some post i noted could help you on that:
https://andrewlock.net/creating-a-custom-error-handler-middleware-function/)
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-8.0)
[https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-8.0)
RFC Specification
https://www.rfc-editor.org/rfc/rfc791
https://code-maze.com/global-error-handling-aspnetcore/
Handle errors in ASP.NET Core
Discover how to handle errors in ASP.NET Core apps.
Handle errors in ASP.NET Core web APIs
Learn about error handling with ASP.NET Core web APIs.
Marinko Spasojević
Code Maze
Global Error Handling in ASP.NET Core Web API - Code Maze
Find out how to replace try-catch blocks in your code with the Global Error Handling by using the custom or built-in middleware in ASP.NET Core.