I am referring to https://community.apigee.com/questions/11381/correct-way-to-return-error-from-javascript-policy.html
I tried to raise Fault using a similar code.But faults are not raised instead the proxy continues with next policy.
Here is my code:
try { var errjsResponse=context.getVariable("serviceCalloutResponse.content"); throw (errjsResponse); } catch (errjsResponse) { print(errjsResponse); var errorResponse =JSON.parse(errjsResponse); if (errorResponse.error_code == 104) { print("I am into 104"); errorContent = {"error_code":"104","error_type":"invalid_request","error_description":errorResponse.error_description, "more_info": "Mandatory parameter/s are missing from request"} ; errorContentjso=JSON.stringify(errorContent); print(errorContentjso); errorStatus =400; print(errorStatus); errorReason ="Bad Request"; } else if (errorResponse.error_code == 110) { errorContent = {"error_code":"110","error_type":"invalid_apiKey","error_description":errorResponse.error_description, "more_info": "ApiKey is invalid"} ; errorStatus =401; errorReason ="invalid_apiKey"; } else if ((errorResponse.error_code == 111) ||(errorResponse.error_code == 112)) { errorContent = {"error_code":"111","error_type":"invalid_authorization","error_description":errorResponse.error_description, "more_info": "Authorization header is invalid."} ; errorStatus =401; errorReason ="invalid_authorization"; } context.setVariable("error.status.code", errorStatus); context.setVariable("error.reason.phrase", errorReason); context.setVariable("error.header.Content-Type", "application/json"); context.setVariable("error.content", errorContentjso); print(errorContentjso); }
I thought by setting error.status.code and other variables,it should throw the error that I have defined.But eventhough I see that these variables are set,its not throwing any error.
I want to know what am I missing...Please guide me..
Try setting the following variables:
context.setVariable("response.status.code", errorStatus); context.setVariable("response.content", errorContentjso);
@RK4 i tried a simple JS with :
print("i am here inside JS");
throw "Test";
The above raises a fault and the Proxy enters the error flow without moving to the next policy.
I feel the issue with your snippet is the catch block. In this case the Exception is caught in the JS itself and the flow exits JS successfully and hence continues with the next policy.
@arghya das...This has not worked for me...
context.setVariable("response.status.code", errorStatus); context.setVariable("response.content", errorContentjso);
@arghya das...This has not worked for me...
context.setVariable("response.status.code", errorStatus); context.setVariable("response.content", errorContentjso);
This must be outside of your try - catch block