ExceptionMiddleware
// DtResponse
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BSS_B2B_API.Extensions.ResponseModel
{
public class DtResponse<T>
{
public bool IsSuccess { get; set; } = true;
public string Message { get; set; }
public T Data { get; set; }
}
}
// DtResponseList
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BSS_B2B_API.Extensions.ResponseModel
{
public class DtResponseList<T>
{
public bool IsSuccess { get; set; } = true;
public string Message { get; set; }
public List<T> Data { get; set; }
}
}
//ErorDetails
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BSS_B2B_API.Extensions
{
public class ErorDetails
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
//ExceptionMiddleware
using BSS_B2B_API.Extensions.ResponseModel;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace BSS_B2B_API.Extensions
{
public class ExceptionMiddleware
{
private RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
DtResponseList<object> result = new();
try
{
await _next(httpContext);
}
catch (Exception e)
{
await HandleExceptionAsync(httpContext, e);
}
}
private Task HandleExceptionAsync(HttpContext httpContext, Exception e)
{
httpContext.Response.ContentType = "application/json";
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
//httpContext.Response.StatusCode = (int)HttpStatusCode.OK;
string message = e.Message;
return httpContext.Response.WriteAsync(new ErorDetails
{
IsSuccess = false,
Message = message
}.ToString());
}
}
}
//ExceptionMiddlewareExtensions
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BSS_B2B_API.Extensions
{
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<ExceptionMiddleware>();
}
}
}Last updated



