44 lines
1.2 KiB
Markdown
44 lines
1.2 KiB
Markdown
|
|
# Responsable Errors
|
||
|
|
|
||
|
|
This is a small go library that provides errors that can be more useful in the context of a web app.
|
||
|
|
|
||
|
|
## Overview
|
||
|
|
|
||
|
|
Use this library to wrap errors so that an error handler in your web app can use them in a response.
|
||
|
|
|
||
|
|
I plan to create a middleware library for Gin soon to utilize this library.
|
||
|
|
|
||
|
|
## Installation
|
||
|
|
|
||
|
|
Use go modules.
|
||
|
|
|
||
|
|
```go
|
||
|
|
import errors "codeberg.org/danjones000/responsable-errors"
|
||
|
|
```
|
||
|
|
|
||
|
|
## Usage
|
||
|
|
|
||
|
|
```go
|
||
|
|
err := SomethingThatReturnsAnError()
|
||
|
|
err = errors.Errorf(418, "I am a teapot. %w", err)
|
||
|
|
|
||
|
|
// Later on, when you're returning something
|
||
|
|
// This example uses gin.
|
||
|
|
c.JSON(err.GetStatus(), gin.H{"error":err.GetMsg()})
|
||
|
|
```
|
||
|
|
|
||
|
|
Or:
|
||
|
|
|
||
|
|
```go
|
||
|
|
user, err := db.GetUser(id)
|
||
|
|
if err != nil {
|
||
|
|
return errors.NotFound("%w", err).Msg("User %d not found", id)
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
In the second example, `err.GetStatus()` returns 404, `err.GetMsg()` returns "User XX not found", and `err.Error()` returns the error message from the original error. Also, `err.Unwrap()` will return the original error, but you'll have to type cast to `UnwrappableError` first.
|
||
|
|
|
||
|
|
## Future plans
|
||
|
|
|
||
|
|
I'm thinking about making the errors able to return a default body from `json.Marshal`, possibly with an optional override.`
|