...

Source file src/github.com/go-kivik/kivik/v4/pouchdb/bindings/errors.go

Documentation: github.com/go-kivik/kivik/v4/pouchdb/bindings

     1  // Licensed under the Apache License, Version 2.0 (the "License"); you may not
     2  // use this file except in compliance with the License. You may obtain a copy of
     3  // the License at
     4  //
     5  //  http://www.apache.org/licenses/LICENSE-2.0
     6  //
     7  // Unless required by applicable law or agreed to in writing, software
     8  // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     9  // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    10  // License for the specific language governing permissions and limitations under
    11  // the License.
    12  
    13  //go:build js
    14  
    15  package bindings
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  
    21  	"github.com/gopherjs/gopherjs/js"
    22  	"github.com/gopherjs/jsbuiltin"
    23  
    24  	internal "github.com/go-kivik/kivik/v4/int/errors"
    25  )
    26  
    27  type pouchError struct {
    28  	*js.Object
    29  	Err     string
    30  	Message string
    31  	Status  int
    32  }
    33  
    34  // NewPouchError parses a PouchDB error.
    35  func NewPouchError(o *js.Object) error {
    36  	if o == nil || o == js.Undefined {
    37  		return nil
    38  	}
    39  	status := o.Get("status").Int()
    40  	if status == 0 {
    41  		status = http.StatusInternalServerError
    42  	}
    43  
    44  	var err, msg string
    45  	switch {
    46  	case o.Get("reason") != js.Undefined:
    47  		msg = o.Get("reason").String()
    48  	case o.Get("message") != js.Undefined:
    49  		msg = o.Get("message").String()
    50  	default:
    51  		if jsbuiltin.InstanceOf(o, js.Global.Get("Error")) {
    52  			return &internal.Error{Status: status, Message: o.Get("message").String()}
    53  		}
    54  	}
    55  	switch {
    56  	case o.Get("name") != js.Undefined:
    57  		err = o.Get("name").String()
    58  	case o.Get("error") != js.Undefined:
    59  		err = o.Get("error").String()
    60  	}
    61  
    62  	if msg == "" && o.Get("errno") != js.Undefined {
    63  		switch o.Get("errno").String() {
    64  		case "ECONNREFUSED":
    65  			msg = "connection refused"
    66  		case "ECONNRESET":
    67  			msg = "connection reset by peer"
    68  		case "EPIPE":
    69  			msg = "broken pipe"
    70  		case "ETIMEDOUT", "ESOCKETTIMEDOUT":
    71  			msg = "operation timed out"
    72  		}
    73  	}
    74  
    75  	return &pouchError{
    76  		Err:     err,
    77  		Message: msg,
    78  		Status:  status,
    79  	}
    80  }
    81  
    82  func (e *pouchError) Error() string {
    83  	return fmt.Sprintf("%s: %s", e.Err, e.Message)
    84  }
    85  
    86  func (e *pouchError) HTTPStatus() int {
    87  	return e.Status
    88  }
    89  

View as plain text