I wrote a code but for some reason it doesn't work...can you tell me what's wrong? I want the app not to stop when I get an exception, only to send that exception back as a json message.
Startup.cs Configure method:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API");
});
}
//this is the question...?
app.UseExceptionHandler(c => c.Run(async context =>
{
var exception = context.Features.Get<IExceptionHandlerPathFeature>().Error;
var response = new { Msg = exception.Message };
await context.Response.WriteAsJsonAsync(response);
}));
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<EventHub>("/events");
});
}
Logic the method where I throw an exception:
public IEnumerable<object> Search(string text)
{
if (text.Length >= 3)
{
var result = new List<object>
{
clubRepository.GetAll().Where(club => club.ClubName.Contains(text)),
playerRepository.GetAll().Where(player => player.PlayerName.Contains(text)),
managerRepository.GetAll().Where(manager => manager.ManagerName.Contains(text)),
stadiumRepository.GetAll().Where(stadium => stadium.StadiumName.Contains(text))
};
return result;
}
else
{
throw new ArgumentException("The text is not long enough!");
}
}
So I would like to get this exception message as json!
Now it is happening --> Image1
I want that to happen --> Image2