简体   繁体   中英

Send class object to Exception Handling

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM