Lord Vermillion
Lord Vermillion

Reputation: 5424

Web API error handeling return json

I have a Web-API where i have many functions that returns objects as JSON, example:

[HttpGet]
public userDTO User(int id)
{
    return dal.GetUser(id);
}

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        }
    }

How can i implement error handeling? If an error occur i want to return a JSON just saying {"error": "Something went wrong"}

Now the API just returns 500 error if something crashes.

Upvotes: 1

Views: 474

Answers (1)

Federico Dipuma
Federico Dipuma

Reputation: 18295

Your best option is to implement a custom ExceptionHandler

public class MyCustomExceptionHandler : ExceptionHandler
{
    private readonly HttpConfiguration _configuration;

    public MyCustomExceptionHandler(HttpConfiguration config){
        _configuration = config;
    }

    public override void Handle(ExceptionHandlerContext context)
    {
        var formatters = _configuration.Formatters;
        var negotiator = _configuration.Services.GetContentNegotiator();

        context.Result = new NegotiatedContentResult<ErrorResponse>(HttpStatusCode.InternalServerError, new ErrorResponse
            {
                Message = context.Exception.Message,
                CustomProperty = "Something"
            }, negotiator, context.Request, formatters);
    }

    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true; //your logic if you want only certain exception to be handled
    }
}

internal class ErrorResponse
{
    public string Message { get; set; }

    public string CustomProperty { get; set; }
}

And register it inside your WebApiConfig.cs file:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Services.Replace(typeof (IExceptionHandler), new MyCustomExceptionHandler(config));
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

This way you have a fine graded customization of error messages returned in case of an unhandled exception.

Upvotes: 2

Related Questions