500 HTTP Status Code in ASP.NET Core Web API

500 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return 500 Internal Server Error HTTP Status Code in ASP.NET Core Web API Applications with Examples. Please read our previous article discussing How to Configure the Allowed HTTP Methods Globally in ASP.NET Core Web API with Examples.

500 HTTP Status Code

The 500 Internal Server Error is a generic HTTP status code indicating that the server encountered an unexpected condition that prevented it from fulfilling the request. This error falls within the range of 5xx error codes, which signify issues on the server side, as opposed to 4xx error codes that indicate client-side errors. Here are some key points about the 500 Internal Server Error:

  • Cause: The error is usually caused by a problem with the website’s server or the server’s programming. It can be triggered by a variety of issues, such as server misconfigurations, software errors, or resource exhaustion.
  • Diagnosis: Pinpointing the exact cause of a 500 error can be difficult for end-users since the server provides no specific information about the error’s nature. Website administrators typically need to investigate the server logs, configuration files, and application code to identify the root cause.
  • Resolution: Resolving a 500 Internal Server Error requires action on the part of the website administrator or hosting provider. Common fixes include correcting server configuration settings, updating or repairing web application code, and increasing server resources.
  • User Action: When users encounter a 500 error, there is little they can do to resolve the issue themselves. Refreshing the page, clearing the browser cache, or returning to the website at a later time might work if the issue is temporary. If the problem persists, contacting the website directly to report the issue can be helpful.
How to Return 500 HTTP Status Code in ASP.NET Core Web API

To return a 500 Internal Server Error HTTP status code in an ASP.NET Core Web API, you can follow these steps. The 500 Status Code is typically used to indicate that an unexpected condition was encountered by the server, and it prevented the request from being fulfilled. This response is often used when the exact error condition is unknown or does not fit any other error condition.

Using StatusCode Method:

The StatusCode method allows you to return a specific HTTP status code. To return a 500 Status Code, you can use it in your controller action. So, please modify the Employee Controller as follows. Here, we have written the code in such a way that at runtime it will Divide By Zero Exception.

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetEmployee()
        {
            try
            {
                // Your logic here
                int x = 10, y = 0;
                int z = x / y; //This statement will throw exception
                return Ok();
            }
            catch (Exception ex)
            {
                // Log the exception details
                
                var customResponse = new
                {
                    Code = 500,
                    Message = "Internal Server Error",

                    // Do not expose the actual error to the client
                    ErrorMessage = ex.Message
                };

                return StatusCode(StatusCodes.Status500InternalServerError, customResponse);
            }
        }
    }
}

Now, if you access the above endpoint, you will get the following response:

How to Return 500 HTTP Status Code in ASP.NET Core Web API

Using ObjectResult Directly:

You can directly return an ObjectResult with a status code of 500. This is useful if you want to return additional information about the error. For a better understanding, please modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetEmployee()
        {
            try
            {
                // Your logic here
                int x = 10, y = 0;
                int z = x / y; //This statement will throw exception
                return Ok();
            }
            catch (Exception ex)
            {
                // Log the exception details
                
                var customResponse = new
                {
                    Code = 500,
                    Message = "Internal Server Error",

                    // Do not expose the actual error to the client
                    ErrorMessage = ex.Message
                };

                return new ObjectResult(customResponse) 
                { 
                    StatusCode = StatusCodes.Status500InternalServerError 
                };
                
            }
        }
    }
}

Now, run the application, access the above endpoint, and you will get the same 500 response as the previous example, as shown in the below image:

How to Return 500 Internal Server HTTP Status Code in ASP.NET Core Web API Applications with Examples

Custom Middleware for Global Error Handling:

For a more centralized approach to error handling (which can automatically return a 500 Status Code for unhandled exceptions), you can implement a custom middleware. So, create a class file named ErrorHandlingMiddleware.cs and copy and paste the following code. The following middleware catches any unhandled exceptions thrown during the processing of a request and returns a 500 Internal Server Error response. 

using System.Text.Json;

namespace ReturnTypeAndStatusCodes.Models
{
    public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate _next;

        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                context.Response.ContentType = "application/json";
                var customErrorResponse = new
                {
                    Code = 500,
                    Message = "Internal Server Error Occurred",
                    ExceptionDetails = ex.Message
                };

                //Log the Exception Details

                var responseJson = JsonSerializer.Serialize(customErrorResponse);
                await context.Response.WriteAsync(responseJson);
            }
        }
    }
}
In the above example,
  • RequestDelegate _next: A delegate representing the next middleware in the pipeline. ASP.NET Core processes request through a sequence of middleware, and this _next delegate allows you to pass the request to the next middleware component.
  • Constructor: The constructor accepts a RequestDelegate and assigns it to the _next field. This setup is necessary for invoking the next middleware in the pipeline.
  • Invoke Method: This method is called by the ASP.NET Core framework to execute the middleware.
  • HttpContext context: Represents all HTTP-specific information about an individual HTTP request.
  • try { await _next(context); }: This line attempts to execute the next middleware in the pipeline. If any middleware further down the pipeline throws an exception, it’s caught by the catch block.
  • catch (Exception ex): Catches any type of Exception thrown by the middleware executed within the try block.
Within the Catch block, we are doing the following:

The catch block is responsible for handling the exception. It’s where you can log the exception and prepare the error response.

  • Status500InternalServerError: Sets the HTTP status code of the response to 500, indicating an internal server error.
  • Response.ContentType = “application/json”: Specifies that the response content type is JSON.
  • customErrorResponse: Prepare the response object we want to return to the client.
  • Serialize(customErrorResponse): Serializes the error message into a JSON string. The error message is generic to prevent leaking sensitive information about the application’s internals.
  • Response.WriteAsync(responseJson): Writes the serialized error object to the HTTP response.
Register the Middleware Component into the Request Processing Pipeline:

After creating the middleware, you need to register it in the Program class. The Error Handling middleware should be one of the first components added to the pipeline:

app.UseMiddleware<ErrorHandlingMiddleware>();

Modifying the Employee Controller:

Next, modify the Employee Controller as follows. Here, you can see that we are not handling the exception that causes unhandled exceptions during the program execution, which is going to be handled by the Exception Middleware component.

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetEmployee()
        {
            // Your logic here
            int x = 10, y = 0;
            int z = x / y; //This statement will throw exception
            return Ok();
        }
    }
}

Now, save the changes, run the application, access the above endpoint, and you will get the following 500 responses:

How to Return 500 Internal Server HTTP Status Code in ASP.NET Core Web API

When to Use 500 HTTP Status Code in ASP.NET Core Web API

In ASP.NET Core Web API, the 500 Internal Server Error HTTP status code is used to indicate that the server encountered an unexpected condition that prevented it from fulfilling the request. This error is a generic “catch-all” response for server-side errors, meaning it is not specific to any particular issue. Here are scenarios when you might use the 500 Status Code in your ASP.NET Core Web API:

  • Unhandled Exceptions: If your API code throws an exception not caught within the application, ASP.NET Core will automatically return a 500 Internal Server Error response to the client. This typically indicates an unexpected error in your server’s code or a failure in a service it is trying to use.
  • Failed Operations: If a server-side operation fails for reasons such as database operation failure or external service failure, you might return a 500 Status Code. However, it’s often better practice to catch such exceptions and return a more specific error code if possible.
  • Configuration Errors: Issues with server configuration that prevent the API from functioning correctly could also lead to a 500 Error Response. For example, if your API relies on a connection string to access a database and that connection string is incorrect, resulting in a failed database connection.
  • Middleware Failures: In ASP.NET Core, middleware components are used to handle requests and responses. If a middleware component throws an unhandled exception, it might result in a 500 Status Code being returned to the client.
Best Practices
  • Error Handling Middleware: Use Error Handling middleware to catch exceptions and log them. This middleware can also return a 500 Status Code with a generic error message to the client, avoiding the exposure of sensitive server details.
  • Specific Status Codes: Wherever possible, use more specific HTTP status codes to indicate the nature of the error. For example, use 503 Service Unavailable if an external service your API depends on is down, or 504 Gateway Timeout if your API is timing out due to an external service.
  • Logging and Diagnostics: Always log exceptions and errors that lead to a 500 Status Code. This information is crucial for diagnosing and fixing the underlying problems.
  • User-Friendly Messages: Consider returning a user-friendly error message along with the 500 Status Code. This can be done while ensuring no sensitive information about the server or its configuration is leaked.
  • Security: Ensure that the error messages returned to clients do not expose sensitive information or hints about your application’s internal structure.
  • Centralize Error Handling: Keep error handling logic in one place for easier maintenance and consistency.

In the next article, I will discuss How to Return 501 Not Implemented Error HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return 500 Internal Server Error HTTP Status Codes in ASP.NET Core Web API with Examples. I hope you enjoy this article, “How to Return 500 Internal Server Error HTTP Status Code in ASP.NET Core Web API”.

Leave a Reply

Your email address will not be published. Required fields are marked *