Oleg Sh
Oleg Sh

Reputation: 9013

Swashbuckle.AspNetCore how to describe error response model?

I have a ASP.NET Core v2.1 with Swashbuckle.AspNetCore package.

I have the following model for error response:

public class ErrorResponse
{
    [JsonProperty(PropertyName = "error")]
    public Error Error { get; set; }
}

public class Error
{
    [JsonProperty(PropertyName = "code")]
    public string Code { get; set; }

    [JsonProperty(PropertyName = "message")]
    public string Message { get; set; }

    [JsonProperty(PropertyName = "target")]
    public string Target { get; set; }

    [JsonProperty(PropertyName = "details")]
    public List<ErrorDetail> Details { get; set; }

    [JsonProperty(PropertyName = "innererror")]
    public InnerError InnerError { get; set; }
}

public class ErrorDetail
{
    [JsonProperty(PropertyName = "code")]
    public string Code { get; set; }

    [JsonProperty(PropertyName = "message")]
    public string Message { get; set; }

    [JsonProperty(PropertyName = "target")]
    public string Target { get; set; }
}

public class InnerError
{
    [JsonProperty(PropertyName = "code")]
    public string Code { get; set; }

    [JsonProperty(PropertyName = "innererror")]
    public InnerError NestedInnerError { get; set; }
}

so, for example, if something goes wrong, my API endpoint returns object of type ErrorResponse with appropriate StatusCode:

        if (String.IsNullOrWhiteSpace(token))
        {
            ErrorResponse errorResponse = new ErrorResponse() { Error = new Error() };
            errorResponse.Error.Code = "InvalidToken";
            errorResponse.Error.Target = "token";
            errorResponse.Error.Message = "Token is not specified";
            return new BadRequestObjectResult(errorResponse);
        }

How can i generate appropriate documentations using Swashbuckle.AspNetCore, so, client will know format of response if something goes wrong?

Upvotes: 2

Views: 2749

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17604

Take a look at the readme:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore#explicit-responses


Explicit Responses

If you need to specify a different status code and/or additional responses, or your actions return IActionResult instead of a response DTO, you can describe explicit responses with the ProducesResponseTypeAttribute that ships with ASP.NET Core. For example ...

[HttpPost("{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public IActionResult GetById(int id)

So in your case you should add:
[ProducesResponseType(typeof(ErrorResponse), 400)]
To those actions that return the error, here is some good reading:
https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/conventions

Upvotes: 3

Related Questions