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

孤者浪人 提交于 2020-01-01 14:18:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/11189161/how-to-return-error-message-from-catch-block-right-now-empty-is-returned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!