0

Given an exception filter like this.

    public override void OnException(HttpActionExecutedContext context)
    {
        var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            // what must I change here to return an object
            // similar to the default exception handler?
            Content = new StringContent("THIS IS MY ERROR"),
        };
        throw new HttpResponseException(resp);
    }

The exception reason returned to the client javascript is a plain string.

When an exception is thrown in a default WebApi2 controller, the default reason object returned contains the config, data, headers etc. I can't find an example of how to return all this extra information from my exception filter. I tried checking out the source to no avail...

enter image description here

 $http.get('/mydata')
     .catch(function(reason) { ... do stuff with reason })
     .then(...);

What do I need to change in order to return the same default response rather than just a plain string.

Content = new ... // what goes here.
Jim
  • 14,952
  • 15
  • 80
  • 167
  • I don't have the exact code with me, but I've done this a few times. You'll need to return back an `IHttpActionResult`. With this you can either send back your HTTP status codes of 500, 400, 401, 403, etc. – Rahul Kishore Jul 02 '16 at 11:07
  • Thanks very much: Fermat would be proud – Jim Jul 02 '16 at 15:56

3 Answers3

0

The reason you don't get the error message is your HttpResponseMessage does not contain it.
So you need to add it to respone object

    public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
        }

and in your action, you throw NotImplementedException Exception

[NotImplExceptionFilter]
    public Contact GetContact(int id)
    {
        throw new NotImplementedException("This method is not implemented");
    }

Hope it helps.

tlp
  • 129
  • 2
  • 5
  • 1
    It doesn't really help to explain how the JavaScript data object is returned to the client in the default IHttpActionResult – Jim Jul 02 '16 at 15:14
0

to anyone else with this particular problem.

public override void OnException(HttpActionExecutedContext context)
{
    var exception = context.Exception as DbEntityValidationException;
    if (exception == null)
        return;

    var errors = exception.EntityValidationErrors.SelectMany(_ => _.ValidationErrors);
    var messages = errors.Select(_ => Culture.Current($"{_.PropertyName}:{_.ErrorMessage}"));
    var message = Culture.Current($"{context.Exception.Message}<br/>{string.Join("<br/>", messages)}");

    // create an error response containing all the required detail...
    var response = context.Request.CreateErrorResponse(
         HttpStatusCode.InternalServerError,
         message,
         exception);
    throw new HttpResponseException(response);
}
Jim
  • 14,952
  • 15
  • 80
  • 167
0
public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotSupportedException)
        {
            context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                JsonConvert.SerializeObject(new[] {context.Exception.Message}));
            return;
        }

        string exceptionMessage = null;
        // Validation Related Errors
        if (context.Exception is DbEntityValidationException)
        {
            var typedEx = context.Exception as DbEntityValidationException;
            if (typedEx == null)
                return;
            var errorMessages = typedEx.EntityValidationErrors
                .SelectMany(x => x.ValidationErrors)
                .Select(x => x.ErrorMessage);
            var fullErrorMessage = string.Join("; ", errorMessages);
            exceptionMessage = string.Concat(typedEx.Message, " The validation errors are: ", fullErrorMessage);
        }
        // All Global Exceptions
        var innerException = context.Exception.GetBaseException();
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(JsonConvert.SerializeObject(new
            {
                Data = new
                {
                    IsSuccess = false,
                    StatusCode = 45000,
                    ErrorMessage = exceptionMessage ??
                                   $"{innerException.Message} StackTrace : {innerException.StackTrace}"
                }
            })),
            ReasonPhrase = "Deadly Exception!"
        });
    }

Working Example of an ExceptionFilter.

Biswajit Panday
  • 817
  • 10
  • 20