Sending a formatted error message to a client from a catch block

I use the following code to send an error message to a client from a filter (ActionFilterAttribute).

catch (Exception) { var response = context.Request.CreateResponse(httpStatusCode.Unauthorized); response.Content = new StringContent("User with api key is not valid"); context.Response = response; } 

But the problem is that it is sent only in plain text. I wanted to send it as the current formatting format. Like in json or xml form.

Here I know that this is because I use StringContent (). But how can we write using a custom Error object? For example, the following does not work:

 response.Content = new Error({Message = "User with api key is not valid"}); 

How do we write the code for this? Thanks in advance.

+6
source share
1 answer

I, I found the correct syntax for writing. We can write like this:

 catch (Exception) { var response = context.Request.CreateResponse(HttpStatusCode.NotFound, new Error { Message = "User with api key is not valid"}); context.Response = response; } 
+8
source

Source: https://habr.com/ru/post/919125/


All Articles