Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/alancesar/gin-error-handler-sample
Handling with errors in gin-gonic
https://github.com/alancesar/gin-error-handler-sample
error-handling gin gin-gonic go golang
Last synced: 2 months ago
JSON representation
Handling with errors in gin-gonic
- Host: GitHub
- URL: https://github.com/alancesar/gin-error-handler-sample
- Owner: alancesar
- Created: 2021-11-19T20:43:37.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2022-01-11T21:03:29.000Z (almost 3 years ago)
- Last Synced: 2024-09-30T07:21:59.015Z (3 months ago)
- Topics: error-handling, gin, gin-gonic, go, golang
- Language: Go
- Homepage:
- Size: 8.79 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Handling errors in gin-gonic
## Starting application
```shell
go mod dowload
go run main.go
```## Request
```shell
curl --location --request POST 'http://localhost:8080/api' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": "some-id",
"fail_database": false,
"fail_service": false
}'
```## Errors
There are two errors struct: `database.Err` and `service.Err`.
They implement `error` interface `Error() string` and `Is(target error) bool`,
returning true if `target` is `pkg.InternalErr`.## Middleware
The middleware `ErrorHandlerMiddleware()` get the errors from gin-gonic context.
If present, check if it is a `pkg.InternalErr`.
Case true, return an internal server error; otherwise, return bad request.
This middleware also checks if `err.Err` is a `database.Err` and prints additional logs.## Handler
The `api.Handler` call run `c.Error(err)` to append errors in gin-gonic context.## Additional information
- [errors.Is documentation](https://pkg.go.dev/errors#Is)
- [gin-gonic bindings](https://github.com/gin-gonic/gin#model-binding-and-validation)