0
Hello, I am studying C# and I was trying to do exception treatment using middleware, to send the message and the exception code to the client, but it is not working very well.
Debugging, breakpoint is passing normally in middleware, but is not sending the error to the client. The middleware code is this:
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
await context.Response.WriteAsync(new ErrorDto()
{
StatusCode = context.Response.StatusCode,
Message = ex.Message
}.ToString(), Encoding.UTF8);
}
});
});
public class ErrorDto
{
public int StatusCode { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
and my Startup.Cs is like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
app.UseCors("Desenvolvimento");
else
app.UseHsts();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.ExceptionHandler();
app.UseMvc(opts =>
{
opts.MapRoute(
name: "default",
template: "api/{controller}/{action}/{id?}");
});
}
Would not be
app.UseExceptionHandler()
?– Leandro Angelo