Last active
April 20, 2020 10:35
-
-
Save PradeepLoganathan/08357b35ff18cbbc8437c9794e317c98 to your computer and use it in GitHub Desktop.
Custom ErrorHandler middleware for ASP.Net core API
This file contains hidden or 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
| 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