Reputation: 4596
I want to implement custom exception handling in web API.
I am able to implement some initial implementation, However I want to pass class object to exception to display all attributes. like
class error
{
int error_code
string error_message
string API
}
When some error occur it should show json like
{
"error_code": 0,
"error_message":"Either Your are not authorized or you don't have any project yet.",
"API": "save data"
}
This code only show the message
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
Any suggestion,
Thanks
Upvotes: 0
Views: 219
Reputation: 1248
You just need to give your object as input for the CreateResponse
method. Generate the error response as follows,
return Request.CreateResponse(HttpStatusCode.BadRequest, error,
new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
The web API will automatically json-fies the error
object you passed.
Make sure you set the necessary values in the error
object before you do this.
Hope this helps.
EDIT
Set your HttpStatusCode
as BadRequest
instead of NotFound
since you are generating the exception. It's more appropriate.
Upvotes: 1