© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
3 replies
Kiel

ASP.NET REST APIs with Custom Error Models

Hi all. I'm currently developing a REST API and have a few questions regarding error flow, as well as custom error models. I'd appreciate an answer to any or all of these questions, if possible!


1) There is a guide out there for error handling in REST APIs, https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0, that seems to heavily imply the current paradigm seems to involve entirely exception-based patterns, versus returning (ex.)
BadRequest()
BadRequest()
,
NotFound()
NotFound()
, etc. Is this really the right way to do things now?

2) If the answer to 1) is "no": Are custom error models considered an acceptable practice? The same guide linked above uses an error handle that formats errors as an
RFC 7807
RFC 7807
(?) JSON object. In the past, I have used custom error models and simply returned that object to describe the error code and problem(s)/error(s). Are either types of error models preferred over the other?

3) If custom models are considered an OK practice: How do I avoid redundantly specifying the HttpStatusCode that is set/returned in my error response? Previously, my error returns in my controller methods would look something like this:
// ErrorModel.NotFound sets its HttpStatusCode property to 404/NotFound
if (!_something.Exists(...))
    return NotFound(ErrorModel.NotFound(...));
// ErrorModel.NotFound sets its HttpStatusCode property to 404/NotFound
if (!_something.Exists(...))
    return NotFound(ErrorModel.NotFound(...));

This is redundant because I'm returning NotFound(), which already sets the HttpStatusCode to 404. However, I can't think of a feasible way to set ErrorModel's HttpStatusCode property without this redundant (helper) static method. Is there a best practice for this as well? For example, somehow accessing the currently set HttpStatusCode to set the model's code dynamically?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ AuthZ/AuthN with ASP.NET Minimal APIs
C#CC# / help
3y ago
ASP.NET - Domain Models Validation
C#CC# / help
2y ago
Use Custom Attributes with ASP.NET Identity
C#CC# / help
2y ago
ASP.NET Identity or custom?
C#CC# / help
3y ago