Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
API exception filter returns 200 response code on exception in ASP.NET MVC

I wrote an exception filter for my API to handle exceptions throw in the API:

using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiExceptionFilter : ExceptionFilterAttribute {

    public override void OnException(ExceptionContext context) {

        // First, generate the status code based on the exception type
        HttpStatusCode status = context.Exception switch {
            UnauthorizedAccessException => HttpStatusCode.Unauthorized,
            ArgumentException => HttpStatusCode.BadRequest,
            MissingHeaderException => HttpStatusCode.BadRequest,
            NotFoundException => HttpStatusCode.NotFound,
            _ => HttpStatusCode.InternalServerError,
        };

        // Next, inject the status code and exception message into
        // a new error response and set the result with it
        context.Result = new JsonResult(new ErrorResponse {
            StatusCode = status,
            Message = context.Exception.Message
        });

        // Finally, call the base function
        base.OnException(context);
    }
}

This function intercepts exceptions as expected but the problem I'm having is that it always returns an OK response. How do I ensure that the response includes the exception message and that the response code is a non-200 value?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Instead of returning a JsonResult - which does not expose a status code property to be set - return an ExceptionResult and set the status code like so:

context.Result = new ExceptionResult(context.Exception, true)
{ StatusCode = status };

If you still want to use your ErrorResponse object, just use an object result:

context.Result = new ObjectResult(new ErrorResponse {
    StatusCode = status,
    Message = context.Exception.Message
    })
    // set status code on result
    { StatusCode = status };
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda