I have an API controller endpoint like:
public IHttpActionResult AddItem([FromUri] string name)
{
try
{
// call method
return this.Ok();
}
catch (MyException1 e)
{
return this.NotFound();
}
catch (MyException2 e)
{
return this.Content(HttpStatusCode.Conflict, e.Message);
}
}
This will return a string in the body like "here is your error msg"
, is there any way to return a JSON with 'Content'?
For example,
{
"message": "here is your error msg"
}
Just construct the desired object model as an anonymous object and return that.
Currently you only return the raw exception message.
public IHttpActionResult AddItem([FromUri] string name) {
try {
// call service method
return this.Ok();
} catch (MyException1) {
return this.NotFound();
} catch (MyException2 e) {
var error = new { message = e.Message }; //<-- anonymous object
return this.Content(HttpStatusCode.Conflict, error);
}
}
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