i am using the following code to send out error message to 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 problem is that it sends out in plain text only. I wanted to send it as format of current formatter. Like in form of json or xml.
Here i know that this is because i am using StringContent(). But how can we write using custom Error object? like, the following is not working either:
response.Content = new Error({Message = "User with api key is not valid"});
How do we write code for this? Thanks in advance.
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.
It's fine practice to throw in the catch block. It's questionable practice to do so ignoring the original exception.
The C# try and catch keywords are used to define a try catch block. A try catch block is placed around code that could throw an exception. If an exception is thrown, this try catch block will handle the exception to ensure that the application does not cause an unhandled exception, user error, or crash the application.
Ya, i found the correct syntax of writing. We can write like:
catch (Exception)
{
var response = context.Request.CreateResponse(HttpStatusCode.NotFound,
new Error { Message = "User with api key is not valid"});
context.Response = response;
}
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