...

Source file src/github.com/docker/distribution/registry/api/errcode/handler.go

Documentation: github.com/docker/distribution/registry/api/errcode

     1  package errcode
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  )
     7  
     8  // ServeJSON attempts to serve the errcode in a JSON envelope. It marshals err
     9  // and sets the content-type header to 'application/json'. It will handle
    10  // ErrorCoder and Errors, and if necessary will create an envelope.
    11  func ServeJSON(w http.ResponseWriter, err error) error {
    12  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    13  	var sc int
    14  
    15  	switch errs := err.(type) {
    16  	case Errors:
    17  		if len(errs) < 1 {
    18  			break
    19  		}
    20  
    21  		if err, ok := errs[0].(ErrorCoder); ok {
    22  			sc = err.ErrorCode().Descriptor().HTTPStatusCode
    23  		}
    24  	case ErrorCoder:
    25  		sc = errs.ErrorCode().Descriptor().HTTPStatusCode
    26  		err = Errors{err} // create an envelope.
    27  	default:
    28  		// We just have an unhandled error type, so just place in an envelope
    29  		// and move along.
    30  		err = Errors{err}
    31  	}
    32  
    33  	if sc == 0 {
    34  		sc = http.StatusInternalServerError
    35  	}
    36  
    37  	w.WriteHeader(sc)
    38  
    39  	return json.NewEncoder(w).Encode(err)
    40  }
    41  

View as plain text