Created
November 22, 2020 07:58
-
-
Save sunilkumarmedium/0206f4d07281defebc0d083ccb75e685 to your computer and use it in GitHub Desktop.
ErrorHandlerMiddleware.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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