2

I'm playing a bit with ASP.NET Core. I'm creating a basic webapi. I'd like to show a JSON error when there is a problem.

The printscreen shows want I want on my screen. The only problem is that it's send with a statuscode of 200.

PrintScreen

catch (NullReferenceException e)
{
    return Json(NotFound(e.Message));
}

I could solve it by doing this:

return NotFound(new JsonResult(e.Message) {StatusCode = 404);

But I don't like this because now you can specify statuscode 500 with a NotFound.

Can someone put me in the correct direction?

Sincerely, Brecht

ErazerBrecht
  • 1,583
  • 2
  • 20
  • 37

2 Answers2

5

Can't you do something like return NotFound(e.Message);

Or you might have your own error document format and go for return NotFound(new ErrorDocument(e.message));

If you have to return with a JsonResult then go for something like the following:

return new JsonResult(YourObject) { StatusCode = (int)HttpStatusCode.NotFound };

Now you have full control over response format and your status code too. You can even attach serializer settings if need be. :)

Swagata Prateek
  • 1,076
  • 7
  • 15
  • If I do return NotFound(e.Message); then the error message is displayed as plain text because e.Message is a normal 'string'. My other errors that check the ModelState are in JSON. And it like to have consistency. I created now and class for making errors. I'll post my new solution seperated. Thanks for showing me the way. I was to busy using NotFound(). It totally forgot about just using 'new JsonResult' as return – ErazerBrecht Sep 06 '16 at 17:37
  • 1
    I understand the modelstate checks. If you want a better hand on this, I'd suggest you to use an Exception Filter described a bit about [here](https://docs.asp.net/en/latest/fundamentals/error-handling.html#server-exception-handling). Then all you ever have to worry about is throwing a proper exception and your controllers would look nice without the global try-catch block surrounding the main code. Just a thought. And yes, error consistency is a good thing. :) – Swagata Prateek Sep 06 '16 at 17:40
  • Thank you for posting that link. I will check that out! Have a nice day! – ErazerBrecht Sep 06 '16 at 17:44
3

EDIT: Found a much better solution here on stackoverflow.

Thank you Swagata Prateek for reminding me to just use a return new JsonResult(). I did solve me problem on this way.

public class Error
{
    public string Message { get; }
    public int StatusCode { get; }

    public Error(string message, HttpStatusCode statusCode)
    {
        Message = message;
        StatusCode = (int)statusCode;
    }
}    


[HttpGet("{id}")]
public IActionResult Get(int id)
{
    try
    {
       return Ok(_manager.GetPokemon(id));
    }
    catch (NullReferenceException e)
    {
       var error = new Error(e.Message, HttpStatusCode.NotFound);
       return new JsonResult(error) {StatusCode = error.StatusCode};
    }
}
Community
  • 1
  • 1
ErazerBrecht
  • 1,583
  • 2
  • 20
  • 37