...

Source file src/github.com/go-openapi/errors/parsing.go

Documentation: github.com/go-openapi/errors

     1  // Copyright 2015 go-swagger maintainers
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package errors
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  )
    21  
    22  // ParseError represents a parsing error
    23  type ParseError struct {
    24  	code    int32
    25  	Name    string
    26  	In      string
    27  	Value   string
    28  	Reason  error
    29  	message string
    30  }
    31  
    32  func (e *ParseError) Error() string {
    33  	return e.message
    34  }
    35  
    36  // Code returns the http status code for this error
    37  func (e *ParseError) Code() int32 {
    38  	return e.code
    39  }
    40  
    41  // MarshalJSON implements the JSON encoding interface
    42  func (e ParseError) MarshalJSON() ([]byte, error) {
    43  	var reason string
    44  	if e.Reason != nil {
    45  		reason = e.Reason.Error()
    46  	}
    47  	return json.Marshal(map[string]interface{}{
    48  		"code":    e.code,
    49  		"message": e.message,
    50  		"in":      e.In,
    51  		"name":    e.Name,
    52  		"value":   e.Value,
    53  		"reason":  reason,
    54  	})
    55  }
    56  
    57  const (
    58  	parseErrorTemplContent     = `parsing %s %s from %q failed, because %s`
    59  	parseErrorTemplContentNoIn = `parsing %s from %q failed, because %s`
    60  )
    61  
    62  // NewParseError creates a new parse error
    63  func NewParseError(name, in, value string, reason error) *ParseError {
    64  	var msg string
    65  	if in == "" {
    66  		msg = fmt.Sprintf(parseErrorTemplContentNoIn, name, value, reason)
    67  	} else {
    68  		msg = fmt.Sprintf(parseErrorTemplContent, name, in, value, reason)
    69  	}
    70  	return &ParseError{
    71  		code:    400,
    72  		Name:    name,
    73  		In:      in,
    74  		Value:   value,
    75  		Reason:  reason,
    76  		message: msg,
    77  	}
    78  }
    79  

View as plain text