github.com/erda-project/erda-infra@v1.0.9/providers/legacy/httpendpoints/errorresp/response.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     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 errorresp
    16  
    17  import (
    18  	"encoding/json"
    19  	"net/http"
    20  
    21  	"github.com/erda-project/erda-infra/providers/legacy/httpendpoints"
    22  	"github.com/erda-project/erda-infra/providers/legacy/httpendpoints/i18n"
    23  )
    24  
    25  // ToResp 根据 APIError 转为一个 http error response.
    26  func (e *APIError) ToResp() httpendpoints.Responser {
    27  	return &httpendpoints.HTTPResponse{
    28  		Error:  e,
    29  		Status: e.httpCode,
    30  		Content: httpendpoints.Resp{
    31  			Success: false,
    32  			Err: httpendpoints.ErrorResponse{
    33  				Code: e.code,
    34  				Msg:  e.msg,
    35  			},
    36  		},
    37  	}
    38  }
    39  
    40  // ErrResp 根据 error 转为一个 http error response.
    41  func ErrResp(e error) (httpendpoints.Responser, error) {
    42  	switch t := e.(type) {
    43  	case *APIError:
    44  		return e.(*APIError).ToResp(), nil
    45  	default:
    46  		_ = t
    47  		return New().InternalError(e).ToResp(), nil
    48  	}
    49  }
    50  
    51  // Write 将错误写入 http.ResponseWriter
    52  func (e *APIError) Write(w http.ResponseWriter) error {
    53  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    54  	w.WriteHeader(e.httpCode)
    55  	return json.NewEncoder(w).Encode(httpendpoints.Resp{
    56  		Success: false,
    57  		Err: httpendpoints.ErrorResponse{
    58  			Code: e.code,
    59  			Msg:  e.Render(i18n.NewNopLocaleResource()),
    60  		},
    61  	})
    62  }
    63  
    64  // ErrWrite 根据 error 写入标准错误格式
    65  func ErrWrite(e error, w http.ResponseWriter) error {
    66  	switch t := e.(type) {
    67  	case *APIError:
    68  		return e.(*APIError).Write(w)
    69  	default:
    70  		_ = t
    71  		return New().InternalError(e).Write(w)
    72  	}
    73  }