~samwhited/xmpp

bfe6a15ae14f549ff0f38b29b920750a2c137e0e — Sam Whited 5 years ago be42b03
Add application level XML errors package

Fixes #16
3 files changed, 58 insertions(+), 0 deletions(-)

A errors/doc.go
A errors/errors.go
A errors/example_test.go
A errors/doc.go => errors/doc.go +6 -0
@@ 0,0 1,6 @@
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

// Package errors provides application level XMPP errors.
package errors // import "bitbucket.org/mellium/xmpp/errors"

A errors/errors.go => errors/errors.go +31 -0
@@ 0,0 1,31 @@
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package errors

import (
	"encoding/xml"
)

// New returns an error that formats as the given text and marshals with the
// given XML name and with the text as chardata.
func New(name xml.Name, text string) error {
	return &errorXML{
		XMLName:  name,
		CharData: text,
	}
}

// errorXML is a trivial implementation of error intended to be marshalable and
// unmarshalable as XML.
type errorXML struct {
	XMLName  xml.Name
	InnerXML string `xml:",innerxml"`
	CharData string `xml:",chardata"`
}

// Satisfies the error interface and returns the error string.
func (e *errorXML) Error() string {
	return e.CharData
}

A errors/example_test.go => errors/example_test.go +21 -0
@@ 0,0 1,21 @@
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package errors

import (
	"encoding/xml"
	"fmt"
)

func ExampleError_New() {
	err := &errorXML{
		XMLName:  xml.Name{"http://example.net", "comedy"},
		CharData: "There was a comedy of errors.",
	}
	b, _ := xml.MarshalIndent(err, "", "  ")
	fmt.Println(string(b))
	// Output:
	// <comedy xmlns="http://example.net">There was a comedy of errors.</comedy>
}