2

I try to use middleware to exception handling. I wrote some code, but it is not working. Some thing wrong. In normaly, if I use try catch scope, I can catch the exception. But I couldn't catch in middleware. What is wrong?

I looking result entity in try scope. Result entity have an exception so I try to use if condition. I solve this problem but I think it is not acceptable:)

I throw some exception in my business layer (onion architecture) for example: throw new Exception("have a problem");

And my middleware class in webapi layer. I want to send response some data if I catch error.

My middleware code in below

public class ExceptionHandlingMiddleware
{
    private readonly RequestDelegate _next;

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

    public Task Invoke(HttpContext httpContext)
    {
        try
        {
            var result = _next(httpContext);
            if (result.Exception != null)
                throw result.Exception;
            return result;
        }
        catch (Exception ex)
        {
            return HandleExceptionAsync(httpContext, ex);
        }
    }

    private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = ResponseCode.Alliswell;

        switch (exception)
        {
            case ServiceException _:
                code = ResponseCode.ServiceError;
                break;
            case BusinessException _:
                code = ResponseCode.BusinessError;
                break;
            case DataLayerException _:
                code = ResponseCode.DataLayerError;
                break;
            case EsriServiceException _:
                code = ResponseCode.EsriServiceError;
                break;
        }

        //var result = JsonConvert.SerializeObject(new { error = ex.Message });

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        var responseEntity = new Response<object>
        {
            Data = null,
            Code = code,
            ErrorMessage = exception.Message,
            State = ResponseState.Error
        };
        var result = context.Response.WriteAsync(JsonConvert.SerializeObject(responseEntity));
        return result;
    }
}

1 Answer 1

1

Use async await syntax within the middleware so that any exceptions thrown can be caught

public class ExceptionHandlingMiddleware {
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext httpContext) {
        try {
            await _next(httpContext);
        } catch (Exception ex) {
            await HandleExceptionAsync(httpContext, ex);
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception) {
        var code = ResponseCode.Alliswell;

        switch (exception) {
            case ServiceException _:
                code = ResponseCode.ServiceError;
                break;
            case BusinessException _:
                code = ResponseCode.BusinessError;
                break;
            case DataLayerException _:
                code = ResponseCode.DataLayerError;
                break;
            case EsriServiceException _:
                code = ResponseCode.EsriServiceError;
                break;
        }

        //var result = JsonConvert.SerializeObject(new { error = ex.Message });

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        var responseEntity = new Response<object> {
            Data = null,
            Code = code,
            ErrorMessage = exception.Message,
            State = ResponseState.Error
        };
        await context.Response.WriteAsync(JsonConvert.SerializeObject(responseEntity));
    }
}
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.