Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending formatted error message to client from catch block

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.

like image 567
Sachin Kumar Avatar asked Jun 27 '12 12:06

Sachin Kumar


People also ask

How do you handle errors in catch block?

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.

Is it good practice to throw exception in catch block?

It's fine practice to throw in the catch block. It's questionable practice to do so ignoring the original exception.

What happens if we throw an exception in catch block in C#?

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.


1 Answers

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; 
}
like image 143
Sachin Kumar Avatar answered Sep 20 '22 22:09

Sachin Kumar