1

Currently I have an ExceptionFilterAttribute to handle exceptions on controllers. My API connects to a service (via proprietary TCP/IP). If this service is not reachable I want to return a HTTP 504 response code with a proper error message.

I have figured out how to send a 400

public override void OnException(ExceptionContext context)
{
    if (!MyService.IsConnected)
    {
        context.Result = new BadRequestObjectResult(new ResultInformation() { ResultCode = 2000056, Message = "My service is not reachable" });

    }
    else
    {
        context.Result = new BadRequestObjectResult(new ResultInformation() { ResultCode = 0, Message = context.Exception.Message });
    }
}

How can I change this code to send a 504 and the error message?

2 Answers 2

5

Use ObjectResult and set the status code manually.

//... omitted for brevity

if (!MyService.IsConnected) {
    var info = new ResultInformation() { 
        ResultCode = 2000056, 
        Message = "My service is not reachable" 
    };
    context.Result = new ObjectResult(info) {
        StatusCode = 504
    };
}

//... omitted for brevity

Most of the standard status result types that require an object body are in fact derived from ObjectResult where they set their specific status code. For example BadRequestObjectResult

If you do not need to actually return a response body, you can instead use StatusCodeResult

context.Result = new StatusCodeResult(504);
Sign up to request clarification or add additional context in comments.

3 Comments

This is your answer here. When you need a response body and no other more specific result type will do, use ObjectResult and set the status code manually. If you do not need to actually return a response body, though, you can just use StatusCodeResult.
@ChrisPratt I'll add in that second part as additional info that will be useful to the op
That worked like a charm. BTW I used the StatusCodes enum instead of 504
0

Try this:

context.HttpContext.Response.StatusCode = 504;

1 Comment

This doesn't really help the OP in their particular scenario. They need to return some sort of IActionResult, but don't know which is best. Setting the response status code directly will be potentially overridden by the eventual result type they return.

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.