From the course: Building and Securing RESTful APIs in ASP.NET Core
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Serialize exceptions as JSON - ASP.NET Core Tutorial
From the course: Building and Securing RESTful APIs in ASP.NET Core
Serialize exceptions as JSON
- [Instructor] ASP.NET core returns http 500 if an unhandled exception occurs in your API. This is the right status code to return but it also returns this html document which feels a little weird for a JSON on API. We can improve this behavior by creating an exception filter that will catch any unhandled exception and send the error message back to the client as a nicely formatted JSON response. To do this, let's make a class that represents the error message body. I'll create a folder here called Models. And then I'll create a model called ApiError. We just need a few properties here. We'll say we have a string property called Message and another string called Detail. Now we'll make a folder called Filters. And create a filter called JsonExceptionFilter. A filter is a chunk of code that runs before or after ASP.Net core processes a request. Filters that handle errors and exceptions are called exception filters. And there's a special interface we can implement here called…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.