Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON error message, IActionResult

Tags:

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"
}
like image 853
havij Avatar asked Dec 05 '18 04:12

havij


1 Answers

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);
    }
}
like image 64
Nkosi Avatar answered Oct 11 '22 18:10

Nkosi