简体   繁体   中英

WSO2 Api Manager Custom error messages

I want to customize the error messages sent by api manager, for instance when an access token is missing or expired. I've configured _auth_failure_handler_ to return messages in json as described here , and get responses like:

{"fault":{"code":"900902","message":"Missing Credentials","description":"Required OAuth credentials not provided"}}

I would like to modify the message description and remove the "code" altogether. Is there a way to do this? I've tried tweaking the sequence with no luck.

It is not wise advice to modify the error code. Nevertheless, yes it is possible to modify the payload. Use the filter mediator and Json path and identify the data and use enrich mediator to modify the payload as you want.

You need to target the error codes from https://docs.wso2.com/display/AM260/Error+Handling and update it to your custom JSON messages. For auth token related errors try modify _auth_failure_handler_ as below:

<sequence name="_auth_failure_handler_" xmlns="http://ws.apache.org/ns/synapse">
<property name="error_message_type" value="application/json"/>
<filter source="get-property('ERROR_CODE')" regex="405">
  <then>
      <sequence key="converter"/>
      <drop/>
  </then>
  <else>
  </else>
</filter>
<filter source="get-property('ERROR_CODE')" regex="900901">
    <then>
        <sequence key="invalidCredential"/>
        <drop/>
    </then>
    <else>
    </else>
</filter>
<filter source="get-property('ERROR_CODE')" regex="900902">
    <then>
        <sequence key="missingCredential"/>
        <drop/>
    </then>
    <else>
    </else>
</filter>
<sequence key="_cors_request_handler_"/>

For your case Missing Credential has a 900902 code , so it will match and need to define missingCredential.xml as below :

<?xml version="1.0" encoding="UTF-8"?>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="missingCredential">
    <payloadFactory media-type="json">
        <format>{ "status": "Error","message": "Missing Credentials"  }</format>
    <!--Add your custom message and format here. This will be your output-->
    </payloadFactory>
    <property name="RESPONSE" value="true"/>
    <header name="To" action="remove"/>
    <property name="HTTP_SC" value="401" scope="axis2"/>
    <property name="messageType" value="application/json" scope="axis2"/>
    <send/>
</sequence>

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