Skip to content

Instantly share code, notes, and snippets.

@PradeepLoganathan
Last active April 20, 2020 10:35
Show Gist options
  • Select an option

  • Save PradeepLoganathan/08357b35ff18cbbc8437c9794e317c98 to your computer and use it in GitHub Desktop.

Select an option

Save PradeepLoganathan/08357b35ff18cbbc8437c9794e317c98 to your computer and use it in GitHub Desktop.
Custom ErrorHandler middleware for ASP.Net core API
using System;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
namespace thetalentbot.JobSeeker.Exceptions
{
public class ExceptionHandler
{
private readonly RequestDelegate _next;
public ExceptionHandler(RequestDelegate next)
{
this._next = next;
}
public async Task Invoke(HttpContext context, IHostingEnvironment env)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, env, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, IHostingEnvironment env, Exception exception)
{
string result;
var code = HttpStatusCode.InternalServerError;
if (env.IsDevelopment())
{
var errorMessage = new
{
error = exception.Message,
stack = exception.StackTrace,
innerException = exception.InnerException
};
result = JsonConvert.SerializeObject(errorMessage);
}
else
{
var errorMessage = new
{
error = exception.Message
};
result = JsonConvert.SerializeObject(errorMessage);
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment