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;
}
}