@Override
    public void write(ApiRequest request, PolicyFailure failure, IApiClientResponse response) {
        String rtype = request.getApi().getEndpointContentType();
        response.setHeader("X-Policy-Failure-Type", String.valueOf(failure.getType())); //$NON-NLS-1$
        response.setHeader("X-Policy-Failure-Message", failure.getMessage()); //$NON-NLS-1$
        response.setHeader("X-Policy-Failure-Code", String.valueOf(failure.getFailureCode())); //$NON-NLS-1$
        for (Entry<String, String> entry : failure.getHeaders()) {
            response.setHeader(entry.getKey(), entry.getValue());
        }
        int errorCode = 500;
        if (failure.getType() == PolicyFailureType.Authentication) {
            errorCode = 401;
        } else if (failure.getType() == PolicyFailureType.Authorization) {
            errorCode = 403;
        } else if (failure.getType() == PolicyFailureType.NotFound) {
            errorCode = 404;
        }

        if (failure.getResponseCode() == 0) {
            // If no response code is set in PolicyFailure, then we can set a default error code to ensure
            // the body and HTTP response code match.
            failure.setResponseCode(errorCode);
        } else if (failure.getResponseCode() >= 300) {
            errorCode = failure.getResponseCode();
        }

        response.setStatusCode(errorCode);

        if ("xml".equals(rtype)) { //$NON-NLS-1$
            response.setHeader("Content-Type", "application/xml"); //$NON-NLS-1$ //$NON-NLS-2$
            try {
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
                StringWriter sw = new StringWriter();
                jaxbMarshaller.marshal(failure, sw);
                response.write(sw.getBuffer());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            response.setHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
            try {
                StringWriter sw = new StringWriter();
                mapper.writer().writeValue(sw, failure);
                response.write(sw.getBuffer());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
@see io.apiman.gateway.engine.IPolicyFailureWriter#write(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.beans.PolicyFailure, io.apiman.gateway.engine.IApiClientResponse)
gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultPolicyFailureWriter.java