title: How can I catch an exception and send it as json message?
body: <p>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.</p>
  <p>Startup.cs Configure method:</p>
  <pre><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
              app.UseSwagger();
              app.UseSwaggerUI(c =&gt;
              {
                  c.SwaggerEndpoint(&quot;/swagger/v2/swagger.json&quot;, &quot;My API&quot;);
              });
          }
          //this is the question...?
          app.UseExceptionHandler(c =&gt; c.Run(async context =&gt;
          {
                  var exception = context.Features.Get&lt;IExceptionHandlerPathFeature&gt;().Error;
                  var response = new { Msg = exception.Message };
                  await context.Response.WriteAsJsonAsync(response);
          }));
  
          app.UseHttpsRedirection();
  
          app.UseStaticFiles();
  
          app.UseRouting();
  
          app.UseCors(x =&gt; x
             .AllowAnyMethod()
             .AllowAnyHeader()
             .SetIsOriginAllowed(origin =&gt; true)
             .AllowCredentials());
  
          app.UseAuthentication();
  
          app.UseAuthorization();
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapControllers();
              endpoints.MapHub&lt;EventHub&gt;(&quot;/events&quot;);
          });
      }
  </code></pre>
  <p>Logic the method where I throw an exception:</p>
  <pre><code>public IEnumerable&lt;object&gt; Search(string text)
      {
          if (text.Length &gt;= 3)
          {
              var result = new List&lt;object&gt;
              {
                  clubRepository.GetAll().Where(club =&gt; club.ClubName.Contains(text)),
                  playerRepository.GetAll().Where(player =&gt; player.PlayerName.Contains(text)),
                  managerRepository.GetAll().Where(manager =&gt; manager.ManagerName.Contains(text)),
                  stadiumRepository.GetAll().Where(stadium =&gt; stadium.StadiumName.Contains(text))
              };
  
              return result;
          }
          else
          {
              throw new ArgumentException(&quot;The text is not long enough!&quot;);
          }
      }
  </code></pre>
  <p>So I would like to get this exception message as json!</p>
  <p>Now it is happening --&gt; <a href="https://i.stack.imgur.com/5ApqA.png" rel="nofollow noreferrer">Image1</a></p>
  <p>I want that to happen --&gt; <a href="https://i.stack.imgur.com/qfztw.png" rel="nofollow noreferrer">Image2</a></p>