0

I have created by some example the ErrorController, which is handling Exception. Currently I have this:

[Route("[controller]")]
[ApiController]
[Authorize]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : ControllerBase
{
    public IActionResult ServerError()
    {
        var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        ErrorResponse response;
        
        if (feature != null && feature.Error.GetType() == typeof(HttpResponseException))
        {
            response = new ErrorResponse
            {
                Error = "Error during processing request",
                Message = feature.Error.Message
            };
            HttpContext.Response.StatusCode = ((HttpResponseException) feature.Error).HttpCode;
        }
        else
        {
            response = new ErrorResponse
            {
                Error = "Unexpected Server Error",
                Message = feature?.Error.Message
            };
        }
        
        return Content(JsonSerializer.Serialize(response), "application/json");
    }    
}

So whenever I throw in my method in controllers HttpResponseException, It will read it, and create response with corresponding code. But doing it through this, will log the HttpResponseException, which is not desired behaviour.

I have found solutions with Request.CreateResponse(), but that method does not exists, but when I replicated this method by myself, it is not desired behaviour (because of Swashbuckle/Swagger UI - The returning type is not the model object, but the HttpResponseMessage).

Found also something about ExceptionFilterAttribute, where I produced this code:

public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        if (!(context.Exception is HttpResponseException)) return;
        
        var exception = (HttpResponseException) context.Exception;
        context.Result = new ObjectResult(""){StatusCode = exception.HttpCode};
    }
}

But can't tell where to globally registered (based on this article).

So how to correctly manage returning desired object or some error with code, in a way that it will not be logged as warn?

1 Answer 1

1

Filters are registered globally in the Startup.cs via the options of AddMVC or AddControllersWithViews options.

Another way to handle exceptions globally is using an exception handling middleware which would catch also unexpected exceptions (which is my preferred way).

Sign up to request clarification or add additional context in comments.

2 Comments

At the start I found what I wanted, I have proceed in the end to the ActionResult<> and methods like Ok(), Forbid(), NotFound(), etc... But also wanted to set some to it, thanks the middleware article I have found StatusCode() method. The middleware btw. also looks like something I would use.
You are welcome. The benefit of the middleware is that it even takes care of exceptions which occure outside of the controllers. Like somewhere in the pipeline, misconfiguration etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.