Web
Analytics
Exception handing in web api 2 using example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

How many ways of Exception Handling

1.HttpResponseException

2.HttpError

3.Exception Filters

  1. HttpResponseException Class:

This exception returns any HTTP status code that you specify in the exception constructor.





2. Http Error:

▸CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client.

▸ CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.

CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class.

 

HttpResponseException  Example Source Code

 

 

        [ResponseType(typeof(info))]
        public IHttpActionResult Getinfo(int id)
        {
            info info = db.infoes.Find(id);
            if (info == null)
            {
                var msg= new HttpResponseMessage(HttpStatusCode.NotFound) {

                  Content= new StringContent(string.Format("your search id not avaliable {0}", id)) ,
                  ReasonPhrase="Employee not found"
                };
                throw new HttpResponseException(msg);
            }

            return Ok(info);
        }

 HttpError Example Source Code

 

   [ResponseType(typeof(info))]
        public HttpResponseMessage Getinfo(int id)
        {
            info info = db.infoes.Find(id);
            if (info == null)
            {
                var msg = string.Format("Your search id is not available {0}", id);
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, msg);
              
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, info);
            }

           
        }