new.go (1888B)
1 // GoToSocial 2 // Copyright (C) GoToSocial Authors admin@gotosocial.org 3 // SPDX-License-Identifier: AGPL-3.0-or-later 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package gtserror 19 20 import ( 21 "net/http" 22 ) 23 24 // New returns a new error, prepended with caller function name if gtserror.Caller is enabled. 25 func New(msg string) error { 26 return newAt(3, msg) 27 } 28 29 // Newf returns a new formatted error, prepended with caller function name if gtserror.Caller is enabled. 30 func Newf(msgf string, args ...any) error { 31 return newfAt(3, msgf, args...) 32 } 33 34 // NewResponseError crafts an error from provided HTTP response 35 // including the method, status and body (if any provided). This 36 // will also wrap the returned error using WithStatusCode() and 37 // will include the caller function name as a prefix. 38 func NewFromResponse(rsp *http.Response) error { 39 // Build error with message without 40 // using "fmt", as chances are this will 41 // be used in a hot code path and we 42 // know all the incoming types involved. 43 err := newAt(3, ""+ 44 rsp.Request.Method+ 45 " request to "+ 46 rsp.Request.URL.String()+ 47 " failed: status=\""+ 48 rsp.Status+ 49 "\" body=\""+ 50 drainBody(rsp.Body, 256)+ 51 "\"", 52 ) 53 54 // Wrap error to provide status code. 55 return WithStatusCode(err, rsp.StatusCode) 56 }