Blake Rivell Blake Rivell - 2 years ago 292
ASP.NET (C#) Question

Error handling in ASP.NET Core 1.0 Web API (Sending ex.Message to the client)

I have an ASP.NET Core 1.0 Web API application and trying to figure out how to pass the exception message to the client if a function that my controller is calling errors out.

I have tried so many things, but nothing implements IActionResult.

I don't understand why this isn't a common thing that people need. If there truthfully is no solution can someone tell me why?

I do see some documentation out there using HttpResponseException(HttpResponseMessage), but in order to use this I have to install the compat shim. Is there a new way of doing these things in Core 1.0?

Here is something I have been trying with the shim but it isn't working:

// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
Customer c = _customersService.GetCustomerById(id);
if (c == null)
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
Content = new StringContent("Customer doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound


throw new HttpResponseException(response);

//return NotFound();
return new ObjectResult(c);

When the HttpResponseException is thrown, I look on the client and can't find the message I am sending anything in the content.

Set Set
Answer Source

Here is an simple error DTO class

public class ErrorDto
    public int Code {get;set;}
    public string Message { get; set; }

    // other fields

    public override string ToString()
        return JsonConvert.SerializeObject(this);

And then using the ExceptionHandler middleware:

            app.UseExceptionHandler(errorApp =>
                errorApp.Run(async context =>
                    context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
                    context.Response.ContentType = "application/json";

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                        var ex = error.Error;

                        await context.Response.WriteAsync(new ErrorDto()
                            Code = <your custom code based on Exception Type>,
                            Message = ex.Message // or your custom message
                            // other custom data
                        }.ToString(), Encoding.UTF8);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download