protected function send_error($ex = null) {
        if ($ex) {
            $info = $ex->getMessage();
            if (debugging() and isset($ex->debuginfo)) {
                $info .= ' - '.$ex->debuginfo;
            }
        } else {
            $info = 'Unknown error';
        }

        // Initialise new DOM document object.
        $dom = new DOMDocument('1.0', 'UTF-8');

        // Fault node.
        $fault = $dom->createElement('SOAP-ENV:Fault');
        // Faultcode node.
        $fault->appendChild($dom->createElement('faultcode', 'MOODLE:error'));
        // Faultstring node.
        $fault->appendChild($dom->createElement('faultstring', $info));

        // Body node.
        $body = $dom->createElement('SOAP-ENV:Body');
        $body->appendChild($fault);

        // Envelope node.
        $envelope = $dom->createElement('SOAP-ENV:Envelope');
        $envelope->setAttribute('xmlns:SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
        $envelope->appendChild($body);
        $dom->appendChild($envelope);

        $this->response = $dom->saveXML();
        $this->send_response();
    }