0

I have something like this using MVC5:

Namespace Controllers
Public Class WorkflowsController Inherits ApiController

    <HttpPost>
    <ActionName("SaveComment")>
    Public Function PostComment(id As String, Optional comment As String = "")
        Try
            Dim status As ApiResponse = SomeClass.AddComment(id, comment)

            Return Me.Json(status)
        Catch ex As Exception
            Return Me.Json(New ApiResponse With {.ErrorMessage = ex.Message})
        End Try
    End Function    
End Class
End Namespace

It works fine, and as you can see, it returns a json object to the browser in both normal and error conditions. In the case of the exception, how can I set the response code to 500 as well as returning the ErrorMessage as a json object?

davecove
  • 1,001
  • 4
  • 16
  • 36
  • Here is a C# version of it [Show exception message to client side](https://stackoverflow.com/a/46532062/40521) Remove the `if` condition for the `X-Requested-With` header and it should work for all requests – Shyju Feb 05 '18 at 19:30
  • Why return a 500 response code if your ApiResponse already handles error messages ? – McX Feb 06 '18 at 13:15

1 Answers1

1

You could execute a HttpStatusCodeResult before returning your JsonResult :

    Try
        Dim status As ApiResponse = SomeClass.AddComment(id, comment)

        Return Me.Json(status)
    Catch ex As Exception
        (New HttpStatusCodeResult(500)).ExecuteResult(ControllerContext)
        Return Me.Json(New ApiResponse With {.ErrorMessage = ex.Message})
    End Try
McX
  • 1,296
  • 2
  • 12
  • 16