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.
Error handling refers to the response and recovery procedures from error conditions present in a software application. In other words, it is the process comprised of anticipation, detection and resolution of application errors, programming errors or communication errors.
The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.
With a custom error handler, you can choose what to do with an error, whether it may be as simple as logging the error to console or sending the error to another error monitoring service. Below is an example of using a custom error handler to log errors: Java.
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); } }); });
Yes it is possible to change the status code to whatever you need:
In your CustomExceptionFilterAttribute.cs file modify the code as follows:
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { var exception = context.Exception; context.Result = new ContentResult { Content = $"Error: {exception.Message}", ContentType = "text/plain", // change to whatever status code you want to send out StatusCode = (int?)HttpStatusCode.BadRequest }; } }
That's pretty much it.
If you have custom exceptions, then you can also check for them when grabbing the thrown exception from the context. Following on from that you can then send out different HTTP Status Codes depdending on what has happened in your code.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With