Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error message from Catch block. Right now empty is returned

My sample code of ApiKey validation is given below (I am using MVC4 web api RC):

public class ApiKeyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        //read api key from query string
        string querystring = context.Request.RequestUri.Query;
        string apikey = HttpUtility.ParseQueryString(querystring).Get("apikey");

        //if no api key supplied, send out validation message
        if (string.IsNullOrWhiteSpace(apikey))
        {                
            var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
            throw new HttpResponseException(response);
        }
        else
        {          
             try
            {
                GetUser(decodedString); //error occurred here
            }
            catch (Exception)
            {
                var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "User with api key is not valid" });
                throw new HttpResponseException(response);
            }
        }
    }
}

Here problem is with Catch block statement. I Just wanted to send custom error message to user. But nothing is sent. It displays a blank screen

However, the statement below is working well and sends out the validation error message correctly:

if (string.IsNullOrWhiteSpace(apikey))
{                
    var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
    throw new HttpResponseException(response);
}

Is there anything that i am doing wrong.

like image 499
Sachin Kumar Avatar asked Dec 13 '22 01:12

Sachin Kumar


1 Answers

I was having the same issue in the exact same scenario. However, in this scenario, you need to return some content in your response to be shown and not really throw the exception. So based on this, I would change your code to the following:

 catch (Exception)
 {
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized);
    response.Content = new StringContent("User with api key is not valid");
    context.Response = response;
 }

So with this change you are now returning your response, with content that will displayed in place of the blank screen.

like image 112
Paige Cook Avatar answered Apr 13 '23 00:04

Paige Cook