From 1a9fcd629a5c79991ad1edfee0379376e5f90c7d Mon Sep 17 00:00:00 2001 From: Jan Semmelink <jan@uafrica.com> Date: Fri, 17 Sep 2021 13:54:26 +0200 Subject: [PATCH] Updated readme with HTTP info --- errors/README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/errors/README.md b/errors/README.md index bcdb840..9190b1e 100644 --- a/errors/README.md +++ b/errors/README.md @@ -59,6 +59,30 @@ if err := db.Select(query); err != nil { } ``` +## func HTTP() +Create an HTTP error, which is the same as others but includes and HTTP Status code: +``` +if err := db.Select(query); err != nil { + return errors.HTTP(http.StatusNotFound, err, "cannot read users") +} +``` + +To retrieve the code, use err.Code() which returns integer value. + +If you wrapped an HTTP error in another HTTP error, there may be different codes in the stack. +The Code() method will dig down all the causes and return the lowest non-zero code value it finds. +So StatusNotFound (404) will have precedence over StatusInsufficientStorage (507) +It will return 0 when there are no codes in the error stack. + +An error with HTTP code will also print the code in the stack, e.g.: +``` + http-error_test.go:27: failed: + http-error_test.go(24): TestHTTPError() terrible mistake HTTP(404:Not Found), because + http-error_test.go(21): TestHTTPError() jissis this is bad! HTTP(507:Insufficient Storage), because + http-error_test.go(18): TestHTTPError() failed to get user HTTP(400:Bad Request), because + http-error_test.go(14): TestHTTPError() failed to connect to db +``` + ## Refactoring exiting code Replace all other errors package imports with this package: ``` -- GitLab