Skip to content

Instantly share code, notes, and snippets.

@sunilkumarmedium
Created November 22, 2020 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunilkumarmedium/0206f4d07281defebc0d083ccb75e685 to your computer and use it in GitHub Desktop.
Save sunilkumarmedium/0206f4d07281defebc0d083ccb75e685 to your computer and use it in GitHub Desktop.
ErrorHandlerMiddleware.cs
namespace CleanArchitectureApp.WebApi.Middlewares
{
using CleanArchitectureApp.Application.Exceptions;
using CleanArchitectureApp.Application.Wrappers;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
response.ContentType = "application/json";
var responseModel = new Response<string>() { Succeeded = false, Message = error?.Message };
switch (error)
{
case ApiException e:
// custom application error
response.StatusCode = (int)HttpStatusCode.BadRequest;
break;
case ValidationException e:
// custom application error
response.StatusCode = (int)HttpStatusCode.UnprocessableEntity;
responseModel.Errors = e.Errors;
break;
case KeyNotFoundException e:
// not found error
response.StatusCode = (int)HttpStatusCode.NotFound;
break;
default:
// unhandled error
response.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
var result = JsonSerializer.Serialize(responseModel);
await response.WriteAsync(result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment