ErrorHandlingMiddleware.cs 1.75 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
using MEU.API.Utils;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace MEU.API.MiddleWare
{
    public class ErrorHandlingMiddleware
    {
        public static bool enableDebug = true;
        private readonly RequestDelegate next;
        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context /* other dependencies */)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            if (ErrorHandlingMiddleware.enableDebug)
            {
                var code = System.Net.HttpStatusCode.InternalServerError; 
                var result = JsonConvert.SerializeObject(new { success = false, message = ex });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)code;
                return context.Response.WriteAsync(result);
            }
            else
            {
                var code = System.Net.HttpStatusCode.InternalServerError; // 500 if unexpected
                var result = JsonConvert.SerializeObject(new { success = false, message = "Unexpected error, please contact admin" });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)code;
                return context.Response.WriteAsync(result);
            }

        }
    }
}