Search code examples
c#rest.net-core

How to return a full BadRequest response body with my own error


I am new to API's. I have consumed them, but never had to published my own until now.

I would like to have uniformity in all error responses. I would like to have all my responses (other than 200 range) look the same as the default error response, but when I add my own error, then only my error is returned in Postman.

Illustration:

When a required parameter is not passed for example, there is an auto default response body which look like this:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-118adfb731bbdb32e865873f70487da2-f5994dea1e69866a-00",
    "errors": {
        "Spec": [
            "The Spec field is required."
        ]
    }
}

Note that I am not validating fields and I did not generate the above error message.

When I return a BadRequest() response, in Postman I see a response body also containing the type, status, title and traceId:

API:

public async Task<ActionResult> GetList([FromQuery] SearchCriteria criteria)
{ 
    return BadRequest();  
}

Response:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "Bad Request",
    "status": 400,
    "traceId": 
}

BUT when I add an error message, then only my error message is returned in Postman:

API:

public async Task<ActionResult> GetList([FromQuery] SearchCriteria criteria)
{ 
    return BadRequest(error: new { error = "Unable to return list" });  
}

Response:

{
    "error": "Unable to return list"
}

How can I add my own error message and also still have the type, title, status, and traceId in the response so the user always knows what to expect?


Solution

  • Probably easiest approach would be using ValidationProblem:

    ModelState.AddModelError("return", "Unable to return List");
    return ValidationProblem(ModelState);
    

    Which produces the following response for me:

    {
       "type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
       "title":"One or more validation errors occurred.",
       "status":400,
       "traceId":"00-4091c0b6419e8cc5d4e9cb1da3764f11-d2bc593ce1a51e0a-00",
       "errors":{
          "return":[
             "Unable to return List"
          ]
       }
    }
    

    Otherwise you might need to dabble with methods exposed by ProblemDetailsFactory.