1

Hi I need to catch exceptions for http requests, e.g.:

    [HttpPost("Test")]
    public async Task<ActionResult<TestResponse>> Test(TestRequest request)
    {
        TestResponse result;
        try
        {
           // call 3rd party service
        }
        catch(exception ex)
        {
          result.Errorcode = "Mock" // This Errorcode will be used by client side
        }

        return Ok(result);
    }

now since there are many http requests, I want to use a middleware to globally handle exceptions rather than
writing try-catch statement in each http request as above.

public class Middleware
{
    readonly RequestDelegate next;

    public Middleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await next(httpContext);
        }
        catch (Exception ex)
        {
            // is there a way to pass TestResponse here so I can do  result.Errorcode = "Mock"?
        }
    }
}

I do not know how to assign Errorcode using the middleware approach as I comment out above. Is it possible? Thanks.

5
  • Is TestResponse your ResponseModel? I mean is it your response structure for all of your apis? Commented Jul 7, 2020 at 16:18
  • @ Arsalan Valoojerdi I have an abstract class called BaseResponse which defines the property "ErrorCode", There are multiple classes inherited from BaseResponse for use in different apis, such as TestResponse. Commented Jul 7, 2020 at 16:22
  • You can use a custom exception and catch it in your middleware but you need to rethrow in the catch block of your controller action. Or store values in the HttpContext (this.HttpContext.Items["my-key"] = "my values";) Commented Jul 7, 2020 at 16:24
  • After an exception occurs is there any other data that you want to send to your clients or it's just Error Code? Commented Jul 7, 2020 at 16:30
  • @Arsalan Valoojerdi Just 2 properties - Errorcode & ErrorDetails from the ResponseModel Commented Jul 7, 2020 at 16:32

1 Answer 1

2

If I understand your requirements well I suggest this:

You don't need access TestResponse and you can configure your response in middleware.

public class FailResponseModel
{
    public FailResponseModel(string errorCode, object errorDetails)
    {
        ErrorCode = errorCode;
        ErrorDetails = errorDetails;
    }

    public string ErrorCode { get; set; }

    public object ErrorDetails { get; set; }
}

public class ExceptionHandlerMiddleware
{
    readonly RequestDelegate next;

    public Middleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await next(httpContext);
        }
        catch (Exception ex)
        {
            httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            httpContext.Response.ContentType = "application/json";
            var response =
                JsonConvert.SerializeObject(new FailResponseModel("your-error-code", "your-error-details"));

            await httpContext.Response.WriteAsync(response);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.